Bilal
Bilal

Reputation: 2673

Dynamic values for @Input in Directive from Component (Angular 4, 5, 6)

Input defined in Directive:

@Input items: any[];

Data defined in Component:

data: string[] = ['Item 1', Item 2', 'Item 3'];

Directive used in component template:

<input type="text" myDirective [items]="data">

How can we update values of items in Directive whenever data array is changed in Component?

For example, if the data in Component updated to:

data: string[] = ['Item 1', Item 2', 'Item 3', 'Item 4'];

The 'Item 4' must be accessible inside Directive.

Upvotes: 1

Views: 5913

Answers (2)

Pardeep Jain
Pardeep Jain

Reputation: 86740

You can use getter setter by typescript like this -

private items: any;

@Input() set items(value: any) {

   this._categoryId = value;
   this.doSomething(this._categoryId);

}

get items(): any {

    return this._categoryId;

}
  • Second Method -

or you could simply use ngOnChanges for any changes in the digest cycle like this -

  ngOnChanges(changes: SimpleChanges) {
      /// your changes in the binding
  }

Upvotes: 3

Suren Srapyan
Suren Srapyan

Reputation: 68655

Just pushing data into the array will not be detected by the directive. You need the change the whole reference of the data to a newer array.

Then you can listen to the OnChanges life cycle event on the directive and check the data's value

ngOnChanges(changes: SimpleChanges) {
   /// changes.data
}

Upvotes: 1

Related Questions