组件指令中@Input的动态值(Angular 4,5,6)

时间:2018-06-05 07:30:09

标签: angular angular5 angular6

指令中定义的输入:

@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'必须可在指令内访问。

2 个答案:

答案 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
}