输入数组的变化检测
Change Detection on Input Array
我正在将对象数组输入到从 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 }
为什么我不能使用 setter 拦截输入数组的输入 属性 更改?实现我想要的结果的好的替代方法是什么?
正在运行,请看我的插件: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 {}
我正在将对象数组输入到从 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 }
为什么我不能使用 setter 拦截输入数组的输入 属性 更改?实现我想要的结果的好的替代方法是什么?
正在运行,请看我的插件: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 {}