父组件向子组件传参
app-component-ts
export class AppComponent { public title:string="你的小可爱突然出现"}
2 在父组件中,子组件通过属性接收父组件穿过来的参数
<app-header [title]="title"></app-header>
在子组件中注册引入Input模块
import { Component, OnInit, Input } from '@angular/core';export class HeaderComponent implements OnInit { @Input() title:string }
4 使用
<p>{{title}}</p>
子组件向父组件传参
子组件通过属性接收父组件穿过来的参数
<app-header [run]="run"></app-header> htmlexport class AppComponent { run(id:string){ console.log(id) }}tsapp
子组件通过@Input接收
export class HeaderComponent implements OnInit { @Input() run:any constructor() { } ngOnInit() { }}header
<button (click)="handleClick()">向父传参</button> html handleClick(){ // console.log(1) this.run("1234") } ts header
二.子组件通过@Output向父组件传参
//泛型:任意类型class Person<T>{ emit(msg:T){ console.log(msg); }}var p=new Person<string>();p.emit("msg")
2.1在子组件中导入Output,EventEmitter两个模块
import { Component, OnInit,Input,Output,EventEmitter } from '@angular/core';
2.2子组件中实例化EventEmitter
export class HeaderComponent implements OnInit {... @Output() private outer=new EventEmitter<string>(); }//通过点击事件传参<button (click)="handleClick()">向父传参</button>
2.3子组件中通过EventEmitter实例化的对象outer,广播数据
export class HeaderComponent implements OnInit { @Output() private outer=new EventEmitter<string>(); ... handleClick(){ //outer事件名 emit后面是参数 this.outer.emit("1001011"); }}
2.4父组件中接收事件
//2.父组件中使用<app-header (outer)="getId($event)" ></app-header>export class AppComponent { getId(id:string){ console.log(id) }}