父组件 => 子组件
方法
利用事件派发EventEmitter 和 Output
// parent
<app-child (voted)="onVoted($event)"></app-child>
onVoted(bool) {
// TODO
}
// child
import { EventEmitter, Output } from "@angular/core";
@Output() voted = new EventEmitter();
vote(boolean) {
this.voted.emit(boolean)
}
属性
运用属性绑定 和 Input
// parent
<app-child [name]="parentName"></app-child>
parentName: string="Max"
// child
import { OnInit } from "@angular/core";
@Input() name: string;
ngOnInit() {
console.log(this.name)
}
子组件 => 父组件
方法
运用本地变量 #varName
// child
name: string = "Max";
// parent
<app-child #child></app-child>
<p>{{child.name}}</p>
运用 @ViewChild
// child
name: string = Max;
// parent
import { ChildComponent } from "./app-child.component";
import { ViewChild } from "angular/core";
<app-child></app-child>
<p>{{child.name}}</p>
@ViewChild(ChildComponent) private child: ChildComponent;
使用 Service
父组件和它的子组件共享同一个服务,利用该服务载内部实现双向通信。