2017-08-29 53 views
1

我可以在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") 
    } 
} 
+0

你的構造函數還有什麼?你能詳細說明爲什麼你不想調用構造函數嗎?順便說一句,你可以刪除構造函數,因爲你傳遞@Input()無論如何它已經初始化,當你從AppComponent傳遞它 – brijmcq

+0

我正在使用組件顯示標尺。我希望測量儀的手能夠從一個值流動到另一個值。如果組件每次都重新創建,它總是從零開始。這就是爲什麼我不想每次都重新創建組件的原因。 –

+0

你只需要顯示5個值?我有另一種解決方案,通過不使用ngFor,如果這就是你想要的 – brijmcq

回答

2

問題是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的更多信息。

+0

它的工作原理,但它似乎有點哈克解決方案。不管怎麼說,還是要謝謝你 ! –

+0

@ bartosz.baczek,不客氣,這是框架的設計:) –

+1

@MaximKoretskyi好東西。這種答案是你每天都看不到的。更多理由讓我訪問角度深入:) – brijmcq

0

不,那是不可能的。

每次渲染組件時,都會創建一個新實例。如果您只想執行一次邏輯,請將其從構造函數移至服務。

相關問題