Angular 如何防止在ngFor指令中调用组件的构造函数
我可以在ngFor指令中包含组件吗?这样,当数据发生变化时,就不必每次都调用组件的构造函数了 例如: 我只想更新数据,而不是重新创建组件。打开控制台以更好地了解我的意思 应用组件:Angular 如何防止在ngFor指令中调用组件的构造函数,angular,Angular,我可以在ngFor指令中包含组件吗?这样,当数据发生变化时,就不必每次都调用组件的构造函数了 例如: 我只想更新数据,而不是重新创建组件。打开控制台以更好地了解我的意思 应用组件: @Component({ selector: 'my-app', template: ` <div> <div *ngFor="let value of sourceData"> <fizz [sampleInputValue]="value"
@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);
}
}
@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);
这不会重新创建组件。看
另请参阅以了解有关ngFor trackBy的更多信息。构造函数中还有哪些内容?你能详细解释一下为什么不想调用构造函数吗。顺便说一下,您可以删除构造函数,因为您无论如何都在传递@Input(),当您使用显示仪表的组件从AppComponent am传递它时,它已经初始化。我希望仪表的手能够流畅地从一个值移动到另一个值。若每次都重新创建组件,它总是从零开始。这就是为什么我不想每次都重新创建组件。是否只需要显示5个值?如果你愿意的话,我有另一种解决办法,那就是不使用ngFor。如果你愿意的话,我很乐意听你这么说。对不起,我的问题不够精确。请注意,5个值只是示例-可以显示任意数量的值。在模板中对sourcedata(如sourcedata[0])进行硬编码可以工作,并且不会在创建构造函数后始终调用它。否则,@maxim koretsyki answer是你唯一的选择。它是有效的,但它似乎有点老套。无论如何谢谢你@bartosz.baczek,不客气,这不是黑客行为,这是框架的设计方式:)@MaximKoretskyi好东西。这种回答是你每天都看不到的。更多让我深入访问angular的原因:)@brijmcq,感谢您的支持!访问深度:)