7. 组件通讯
7.1 向组件内部传递数据
<app-favorite [isFavorite]="true"></app-favorite>
复制代码
// favorite.component.ts
import { Input } from '@angular/core';
export class FavoriteComponent {
@Input() isFavorite: boolean = false;
}
复制代码
注意:在属性的外面加 [] 表示绑定动态值,在组件内接收后是布尔类型,不加 [] 表示绑定普通值,在组件内接收后是字符串类型。
<app-favorite [is-Favorite]="true"></app-favorite>
复制代码
import { Input } from '@angular/core';
export class FavoriteComponent {
@Input("is-Favorite") isFavorite: boolean = false
}
复制代码
7.2 组件向外部传递数据
需求:在子组件中通过点击按钮将数据传递给父组件
<!-- 子组件模板 -->
<button (click)="onClick()">click</button>
复制代码
// 子组件类
import { EventEmitter, Output } from "@angular/core"
export class FavoriteComponent {
@Output() change = new EventEmitter()
onClick() {
this.change.emit({ name: "张三" })
}
}
复制代码
<!-- 父组件模板 -->
<app-favorite (change)="onChange($event)"></app-favorite>
复制代码
// 父组件类
export class AppComponent {
onChange(event: { name: string }) {
console.log(event)
}
}
作者:xiaoxiaok
链接:juejin.cn/post/713932…
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。