[英]Angular 2 *ngFor recreates components on every change check
我有兩個嵌套的*ngFor
循環,一個循環遍歷庫,另一個循環遍歷該庫的所有項目,每個項目都有一個角度組件。
現在的問題是,每次對角度進行更改檢查時都會重新創建這些項目組件,我通過將記錄器放置到項目組件的ngOnInit()
處理程序中注意到了這ngOnInit()
。 每當我更改頁面上的任何內容時,都會調用此logger,從而導致組件的狀態被重置並且所有更改都將丟失,因此我無法修改組件的狀態,這完全破壞了應用程序的功能。
我試圖通過使用trackBy: trackByFn
來解決此問題,但這也沒有幫助。
貨櫃
<div *ngFor="let lib of libraries">
<div *ngIf="lib.components.length" class="groupContainer" [class.closed]="!libraryIsOpened(lib)">
<div class="title flex flex-row" (click)="toggleLibrary(lib)">
<p>{{ lib.name === '__none' ? 'No Library' : lib.name }} ({{ lib.components.length }})</p>
<div class="flex flex-grow"></div>
<i class="mdi mdi-chevron-up iconClose"></i>
<i class="mdi mdi-chevron-down iconOpen"></i>
</div>
<div class="content">
<app-component-list-item *ngFor="let c of components; trackBy: trackByFn"
class="flex"
[component]="c">
</app-component-list-item>
</div>
</div>
</div>
清單項目 :
import ...
@Component({
selector: 'app-component-list-item',
templateUrl: './component-list-item.component.html',
styleUrls: ['./component-list-item.component.scss']
})
export class ComponentListItemComponent implements OnInit {
@Input() component: PipelineComponent
constructor(private el: ElementRef, private nodeCreator: NodeCreationService) {
}
ngOnInit() {
console.log('init')
}
trackByFn(index, item) {
return this.component.componentID
}
}
沒有看到更多的代碼,很難確定。 但我懷疑這是因為libraries
正在更改(您是否在使用Redux?這將要求頂級libraries
列表將其更改為任何元素或元素的屬性已更改),因此Angular更改檢測會發現它已更改(並且不是)足夠聰明,知道里面的元素是相同的),因此為每個元素重新創建新的組件。 如果是這種情況,那么您應該在父組件中存儲庫的可變副本,並就地進行更改,以使Angular不會認為在更改一個元素時整個事情都發生了變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.