Angular watch single property of an @Input Array of Objects

1703 views angular

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


One way would be

@Input() isTrue;

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

posted this

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 {
      set list(list:iMyType[]) {
        this._list = list;

posted this

Have an answer?


Please login first before posting an answer.