如何防止在ngFor指令中调用组件的构造函数 [英] How to prevent calling constructor of component in ngFor directive
问题描述
我可以在ngFor指令中包含组件吗,这样,当数据更改时,不必每次都调用该组件的构造函数吗?
Can I have components inside ngFor directive, in such a way, that component's constructor doesn't have to be called every time, when data changes?
插播示例: http://plnkr.co/edit/6A6Aj8yeFqNd28Nl8cyS?p=preview
我只想更新数据,而不是重新创建组件.打开控制台,以更好地理解我的意思.
I just want to update data, not re-create component. Open console to see better what I mean.
AppComponent:
AppComponent:
@Component({
selector: 'my-app',
template: `
<div>
<div *ngFor="let value of sourceData">
<fizz [sampleInputValue]="value"></fizz>
</div>
</div>
`,
})
export class App {
sourceData: number[] = [];
ngOnInit() {
setInterval(() => {
let newArrayOfRandomNumbers: number[] = [
Math.floor(Math.random() * 60) + 1,
Math.floor(Math.random() * 60) + 1,
Math.floor(Math.random() * 60) + 1,
Math.floor(Math.random() * 60) + 1,
Math.floor(Math.random() * 60) + 1
]
newArrayOfRandomNumbers.forEach((randomNumber, index) => {
this.sourceData[index]= newArrayOfRandomNumbers[index];
});
}, 500);
}
}
FizzComponent:
FizzComponent:
@Component({
selector: 'fizz',
template: `
{{sampleInputValue}}
`
})
export class FizzComponent {
@Input()sampleInputValue: number;
constructor() {
console.log("I dont want to be called, I just want the data to be updated")
}
}
推荐答案
问题是Angular使用默认的trackBy函数,该函数按身份进行比较.如果不匹配,它将重新创建组件并因此调用其构造函数.
The problem is that Angular uses default trackBy function that compares by identity. If there is a mismatch it recreates the component and calls it's constructor as a consequence.
您可以利用它,并将具有数字属性的值作为对象传递给ngFor
:
You could leverage that and pass values as object with numeric properties to ngFor
:
sourceData = [{},{},{},{},{}];
ngOnInit() {
setInterval(() => {
let newArrayOfRandomNumbers: number[] = [
Math.floor(Math.random() * 60) + 1,
Math.floor(Math.random() * 60) + 1,
Math.floor(Math.random() * 60) + 1,
Math.floor(Math.random() * 60) + 1,
Math.floor(Math.random() * 60) + 1
]
newArrayOfRandomNumbers.forEach((randomNumber, index) => {
this.sourceData[index].v= newArrayOfRandomNumbers[index];
});
}, 500);
这将不会重新创建组件.参见此导航车.
This will not be re-creating components. See this plunker.
另请参见此答案以了解有关ngFor trackBy的更多信息.
Also see this answer to understand more about ngFor trackBy.
这篇关于如何防止在ngFor指令中调用组件的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!