2016-09-16 62 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。我的错。谢谢! –