2016-09-16 61 views
3

我輸入一個對象數組到一個從HTTP請求響應(異步)生成的組件中,我想用前三個數組元素填充一個不同的數組。我想在第一個數組從父輸入分配的同時填充新數組。輸入數組的變化檢測

這裏是我的代碼無法正常工作:

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 } 

我爲什麼不能攔截使用二傳手的inputed陣列的輸入性質的變化?什麼是實現我想要的結果的好的替代方法?

+0

你能告訴我們如何在父組件中調用它嗎? –

回答

2

這是工作,看我plunker:https://plnkr.co/edit/ZIjepnYZ5IS8FfktU0C1?p=preview

你需要那些images[i]的推到數組,而不是每次都分配給它。

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 {} 
+0

Dangit。我的錯。謝謝! –