指令中定义的输入:
@Input items: any[];
组件中定义的数据:
data: string[] = ['Item 1', Item 2', 'Item 3'];
组件模板中使用的指令:
<input type="text" myDirective [items]="data">
如果在Component中更改items
数组,我们如何在Directive中更新data
的值?
例如,如果Component中的data
更新为:
data: string[] = ['Item 1', Item 2', 'Item 3', 'Item 4'];
'Item 4'
必须可在指令内访问。
答案 0 :(得分:2)
你可以像这样使用getter setter
打字稿 -
private items: any;
@Input() set items(value: any) {
this._categoryId = value;
this.doSomething(this._categoryId);
}
get items(): any {
return this._categoryId;
}
或者你可以简单地使用ngOnChanges
来解决摘要周期中的任何变化 -
ngOnChanges(changes: SimpleChanges) {
/// your changes in the binding
}
答案 1 :(得分:1)
指令不会检测到只是将数据推入数组。您需要将data
的整个引用更改为更新的数组。
然后你可以听指令上的OnChanges
生命周期事件并检查数据的值
ngOnChanges(changes: SimpleChanges) {
/// changes.data
}