组件之间的通信是我们业务开发中少不了的,先了解下父子组件的通信
父组件传数据给子组件
前面,我们学会会动态属性的绑定,所以在父组件中给子组件绑定属性,在子组件中就可以使用这个属性了。
- 父组件中声明然后赋值
export class AppComponent {
money = 100;
}
<main class="main">
<p>Welcome to Angular!{{name}}</p>
<h3>下面是子组件的内容</h3>
<p>这是父组件的存款:{{money}}</p>
<app-user-list [childMoney]="money" />
</main>
- 子组件里面接受这个属性
注意,这里我们使用
@Input()装饰器来接受这个属性。值类型必须保持一致,否则会报错。
import { Component, Input } from '@angular/core';
export class UserListComponent {
@Input() childMoney = 0;
}
显示父组件传过来的值
<p>
这里是子组件的money:{{childMoney}}
</p>
子组件传数据给父组件
- 子组件
<p>这里是子组件的money:{{childMoney}}</p>
<button (click)="handleAdd()">赚钱</button>
<button (click)="handledec()">花钱</button>
const core
里面引入EventEmitter
,用来发射事件。Output
声明一个事件发射器,用来发射事件。
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Output() incrementCountEvent = new EventEmitter<number>();
handleAdd() {
this.incrementCountEvent.emit(1);
}
handledec() {
this.incrementCountEvent.emit(-1);
}
- 父组件
自定义事件,使用()
绑定事件。接受参数,使用$event
来接受。
<app-user-list [childMoney]="money" (incrementCountEvent)="handleChange($event)" />
handleChange($event: any) {
this.money += $event;
}
就完成了子组件向父组件的通讯。