3

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?

1
  • Can you show us how this is called in the parent component? Commented Sep 16, 2016 at 18:34

1 Answer 1

2

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 {}
Sign up to request clarification or add additional context in comments.

1 Comment

Dangit. My mistake. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.