我可以在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