父传子
1.使用@input方式传值
@Input('xxx') 可以接收一个参数用于父组件传值时 [ ] 的名称
1. 在子组件的component.ts中导入Input并声明该变量
1.1 `import {Input} from '@angular/core`
1.2 在构造函数中 @Input() xxx:any; //any可以换成别的类型
2. 在父组件中使用子组件时 如 <app-son [xxx]='fatherData'></app-son>
其中app-son是子组件 fatherData是父组件components中的变量
3. xxx使用和子组件中变量的使用没什么区别
2.使用inputs方式传值
1.在子组件component.ts中
@component({
inputs:['xxx'] //input是用来接收父组件传递的值
})
2.父组件使用子组件时 <app-son [xxx]='fatherData'></app-son>
fatherData是父组件中的变量 不能直接写字符串
3. this.xxx即可正常使用
子传父
1.使用ViewChild
1. 给子组件添加标记
<app-son #son></app-son>
2. 导入ViewChild
import { ViewChild } from '@angular/core';
3. @ViewChild('son',{static:true}) son:any;
4. 可以在html中直接使用 son.methodName 的方式调用子组件中的方法
5. 需要注意的是 son只能在ngAfterViewInit()这个生命周期开始才能使用 只有当页面初始化完成之后 才可以拿到这个子组件
2.使用Output和EventEmitter
1.导入Output和EventEmitter
import { Output,EventEmitter } from ‘@angular/core’;
2.在子组件类中创建事件 在生命周期函数中发送事件
不要写在contructor里面
@Output() 接收一个参数 用于父组件调用时 ( ) 中的名称
@Output() sonEvent=new EventEmitter();
ngOnInit(){
this.sonEvent.emit('data');
}
3.当子组件事件触发时 父组件使用方法接收 必须使用参数 $event接收数据
<app-son (sonEvent)="getSonData($event)"></app-son >
// 父组件的方法
getSonData(event:any){
console.log(event);
}
3.使用outputs
1.在子组件中
@Component({
outputs:['sonEvent']
})
2.在类中定义子组件的事件
public sonEvent:EventEmitter<any>;
3. 在子组件的构造函数中初始化事件
this.sonEvent=new EventEmitter();
4.在需要发送的时候发送事件
this.sonEvent.emit('data');
5.当子组件事件触发时 父组件使用方法接收 必须使用参数 $event接收数据
<app-son (sonEvent)="getSonData($event)"></app-son >
父组件的方法
getSonData(event:any){
console.log(event);
}