Angular_组件间通讯

组件间通讯

1.组件间通讯
父组件向子组件输入属性用

@Input()
amount: number;

2.组件输出属性
1.在发射的组件内部定义发射的EventEmitter对象

@Output()
lastPrice: EventEmitter<PriceQuote> = new EventEmitter();

2.在发射组件里 将要发射的变量发射出去 ,注意类型必须和定义里的泛型一致

let pq = new PriceQuote(this.stockCode, Math.random() * 100);
this.lastPrice.emit(pq);

3.在发射组件标签声明的地方加上监听该emitEvent对象传过来的事件

<app-price-quote (lastPrice)="priceQuoteHandler($event)"></app-price-quote>

然后父组件里就可以写,事件就是发射过来的值

priceQuoteHandler(priceQuote) {
  this.priceQuote = priceQuote;
}

注意想监听事件的名字即不是lastPrice 只要在output里改即可

@Output('priceChange')

但是这样有感觉很麻烦,能不能用双向绑定

还有注意 如果一个属性想用双向绑定 那么如果输入属性为rating ,并且想在标签上[(rating)],获取输出值那么在组件内的输出属性 名称必须为ratingChange ,加个Change

@Output()
private ratingChange: EventEmitter<number> = new EventEmitter();

参考链接

猜你喜欢

转载自blog.csdn.net/wtdask/article/details/81237036