1、父组件给子组件传参(通过属性)
父组件
//.html
<app-header [title]="title"></app-header>
父组件
//.ts
export class AppComponent {
public title:string = "我是Html"
}
子组件通过属性接收父组件传递过来的参数
//子组件中引入Input模块
//.ts
import {Component,OnInit,Input} from '@angular/core'
export class ... {
@Input() title:string;
OnInit(){
}
}
//.html
<p>{{title}}</p>
2、子组件给父组件传参
2-1、方法一(推荐)
//子组件
//.html
<button (click)="handleClick()">向父组件传参</button>
//.ts
import {Component,OnInit,Input} from '@angular/core'
export ... {
@Input() run:any;
...
handleClick(){
this.run("15345")
}
}
//父组件
//.html
<app-header [title]="title" [run]="run"></app-header>
//.ts
run(id:string){
console.log(id)
}
2-2、方法二(子组件通过@Output向父组件传参)
//泛型:任意类型
class Person<T>{
emit(msg:T){
console.log(msg)
}
}
var p = new Person<string>();
p.emit("hello world")
子组件引入Output,EventEmitter
//子组件
//.html
<button (click)="handleClick()">向父组件传参</button>
子组件中实例化EventEmitter
//.ts
import {Component,OnInit,Input,Output,EventEmitter} from '@angular/core'
export ... {
@Output private outer = new EventEmitter<string>();
handleClick(){
this.outer.emit("556484")
}
}
子组件中通过EventEmitter实例化的对象outer,广播数据
//.ts
export ... {
...
handleClick(){
this.outer.emit("556484")
}
}
父组件中接收数据
//父组件
//.html
<app-header [title]="title" (outer)="getId($event)"></app-header>
//.ts
export ... {
getId(id:string){
console.log(id)
}
}