1. 子组件引入 Output 和 EventEmitter;子组件中实例化 EventEmitter;子组件通过 EventEmitter 对象 outer 实例广播数据
import { Component,Input,Output,EventEmitter} from '@angular/core';
@Component({
selector: 'app-son',
templateUrl: './son.component.html',
styleUrls: ['./son.component.css']
})
export class SonComponent implements OnInit {
@Output() private outer=new EventEmitter<string>();
constructor() { }
sendParent(){
this.outer.emit('msg from child')
}
ngOnInit() {
this.sendParent();
}
}
2 父组件调用子组件的时候,定义接收事件 , outer 就是子组件的 EventEmitter 对象 outer
<app-son (outer)="runParent($event)"></app-son>>
3 父组件接收到数据会调用自己的 runParent 方法,这个时候就能拿到子组件的数据
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-father',
templateUrl: './father.component.html',
styleUrls: ['./father.component.css']
})
export class FatherComponent implements OnInit {
public msg2;
constructor() { }
ngOnInit() {
this.msg2 = "test";
}
runParent(msg:string){
this.msg2 = msg;
}
}