Search code examples
angularangular2-changedetection

Change Detection on Input Array


I am inputting an array of objects into a component that are generated from an HTTP request response (asynchronous), and I want to fill up a different array with just the first three array elements.

I want to fill up the new array at the same time as the first array gets assigned from the parent input.

Here's my code that does not work:

private _images: any[];
private threeImages: any[];

@Input() 
set images(images: any[]) {
    this._images = images;
    for(let i=0; i < 3; i++){
        this.threeImages = images[i];
    }
}
get images() { return this._images }

Why can't I intercept input property changes of an inputed array using a setter? And what is a good alternative way to achieve the outcome I want?


Solution

  • It is working, see my plunker: https://plnkr.co/edit/ZIjepnYZ5IS8FfktU0C1?p=preview

    You need to push those images[i]'s to the array instead of assign it every time.

    import {Component, NgModule, Input} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    
    @Component({
      selector: 'my-cmp',
      template: `my-cmp!`,
    })
    export class MyCmp {
    
      private _images: any[];
      private _threeImages: any[];
    
      @Input() set images(images: any[]) {
        this._images = images;
    
        this._threeImages = []; // CLEAR IT !
        for(let i=0; i < 3; i++) {
          this._threeImages.push(images[i]);
        }
    
        console.log(this._images);
        console.log(this._threeImages);
      }
    }
    
    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2>Hello {{name}}</h2>
        </div>
        <my-cmp [images]="myImages"></my-cmp>
      `,
    })
    export class App {
    
      private myImages: any[] = [
        {},
        {},
        {},
        {},
        {}
      ];
    
      constructor() {
        this.name = 'Angular2'
      }
    }
    
    @NgModule({
      imports: [ BrowserModule ],
      declarations: [ App, MyCmp ],
      bootstrap: [ App ]
    })
    export class AppModule {}