我可以在ngFor指令内部使用组件吗?以这种方式,组件的构造函数不必每次都在数据更改时调用?如何防止在ngFor指令中调用组件的构造函数
Plunker例如:http://plnkr.co/edit/6A6Aj8yeFqNd28Nl8cyS?p=preview
我只是想更新数据,而不是重新创建组件。打开控制台以更好地了解我的意思。
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:
@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")
}
}
你的构造函数还有什么?你能详细说明为什么你不想调用构造函数吗?顺便说一句,你可以删除构造函数,因为你传递@Input()无论如何它已经初始化,当你从AppComponent传递它 – brijmcq
我正在使用组件显示标尺。我希望测量仪的手能够从一个值流动到另一个值。如果组件每次都重新创建,它总是从零开始。这就是为什么我不想每次都重新创建组件的原因。 –
你只需要显示5个值?我有另一种解决方案,通过不使用ngFor,如果这就是你想要的 – brijmcq