gpt4 book ai didi

angular - 如何防止在 ngFor 指令中调用组件的构造函数

转载 作者:行者123 更新时间:2023-12-02 01:09:12 24 4
gpt4 key购买 nike

我能否在 ngFor 指令中包含组件,这样,当数据发生变化时,组件的构造函数不必每次都被调用?

Plunker 示例:http://plnkr.co/edit/6A6Aj8yeFqNd28Nl8cyS?p=preview

我只想更新数据,而不是重新创建组件。打开控制台以更好地理解我的意思。

应用组件:

@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);
}
}

Fizz组件:

@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 函数来比较身份。如果不匹配,它会重新创建组件并调用它的构造函数。

您可以利用它并将值作为具有数字属性的对象传递给 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 plunker

另请参阅 this answer 以了解有关 ngFor trackBy 的更多信息。

关于angular - 如何防止在 ngFor 指令中调用组件的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45940888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com