一)子组件传值到父组件
1.EventEmitter和Output装饰器配合使用,指定广播传递的参数类型变量
子组件传递的是一个字符串,可以根据相应的需求定义成如数字,数组,对象等类型。
import { Output, EventEmitter } from '@angular/core';
@Output() private childOuter = new EventEmitter<string>();
@Output() private childOuter2 = new EventEmitter<string>();
sendParent(){
this. childOuter.emit('msg from child'); // 广播传递数据给父组件
this. childOuter2.emit('msg from child2');
}
2.父组件监听子组件的事件, (childOuter)和(childOuter2)就是子组件的EventEmitter对象
因为父组件可以使用多个子组件,也就相当于一个子组件能调用父组件的不同方法
<child (childOuter) ="runParent($event)"></child>
<child (childOuter2) ="runParent2($event)"></child>
3.在父组件ts接收子组件传递过来的数据
msg = any;
runParent(msg:string){
this.msg = msg;
}
runParent2(msg:string){
this.msg = msg;
}
二)父组件传值到子组件
1. 父组件使用子组件
父组件ts里定义需要传递的数据变量:
fatherMsg: string;
this. fatherMsg = ‘字符串’;
使用子组件:
<child [childMsg]="fatherMsg "></child>
childmsg是子组件接收数据的标识符,fatherMsg是父组件传递的数据的标识符。父组件传递的是一个字符串,可以根据相应的需求定义成如数字,数组,对象等类型。
2.子组件使用@input接收父组件的数据
import { input } from '@angular/core';
@Input() fatherMsg:string;
childMsg = any;
demo(){
// 子组件内使用父组件传递过来的数据
this. childMsg = fatherMsg;
}
子组件在页面使用父组件的数据的时候可以使用{{ fatherMsg }}。
三)父组件调用子组件方法
1.子组件提供方法给父组件使用
接收字符串变量,可以根据相应的需求定义成如数字,数组,对象等类型。
demo( fatherMsg: string){
console.log(‘fatherMsg: ‘ + fatherMsg);
}
2. 父组件使用子组件
<child #child1 ></child>
3. 父组件ts获得子组件的引用
定义测试数据
childData1: ‘child1’;
childData2: ’child2’;
声明一个由viewChild装饰器装饰的变量父组件中获得子组件#的引用
import { Output, EventEmitter } from '@angular/core';
@ViewChild('child1')
child1:Child1Component;
//ts内使用子组件的demo方法
this.child1.demo(childData1);
在页面使用子组件的demo方法
<child #child2 ></child>
<button (click)="child2.demo(childData2)">调用child2的demo方法</button>