Angular watch single property of an @Input Array of Objects

1703 views angular
1

I have an Angular Component that get as it's @Input and Array of Objects. I would like to Watch for changes (change detection) of a single property of an Object inside an Array passed via @Input.

export interface iMyType {
  data: any; // don't care if this changed
  isTrue: boolean; // I want to react on changes of this property
}
...
@Input() list: iMyType[];

I know about KeyValueDiffer and about KeyValueDiffer which allows my to watch changes on Object properties or Array length. But how can I watch only a single property of the Object.

Naive solution - Bad solution:

watch for all changes, but react only if change is on selected property.

_diffObj: KeyValueDiffer;
...
ngDoCheck() {
  _.forEach(this.list, item => {
    const changes = this._diffObj.diff(item);
    if (changes) {
      changes.forEachChangedItem((change) =>
      {
        if (change.currentValue != change.previousValue)
        {
          if (change.key === 'isTrue')
          {
             // Enter onChange code here...
          }
        }
    }
  });
}

answered question

2 Answers

7

One way would be

@Input() isTrue;

ngOnChanges(changes: SimpleChanges) {
    if (changes['isTrue']) { 
      // your code
    }
  }

posted this
11

You can use ngOnChanges which will be called on every updates of your @Inputs.

If you want to detect only the updates of the @Input "isTrue" you could use a setter:

    export class SubComponent {
      @Input()
      set list(list:iMyType[]) {
        this._list = list;
        console.log(list[0].isTrue);
     }  
   }

posted this

Have an answer?

JD

Please login first before posting an answer.