每当用户创建新标签页时,我都会尝试以编程方式更改为下一个标签。但是,我无法让它发挥作用。我看到github discussion表示我仍然应该在重复的[selected]
元素上使用<p-tabPanel>
输入,但我似乎无法正确使用它。在创建另一个标签时,我最终收到TabPanel.html:2
的错误。
Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.
模板代码:
<p-tabView [controlClose]="true" (onClose)="deletePiece($event)" [activeIndex]="selectedTabIndex">
<p-tabPanel [header]="'Piece ' + i" *ngFor="let piece of pieceCollection; let i = index" [closable]="true" [selected]="i == selectedTabIndex" (click)="setSelectedTabIndex(i)">
{{ tabContent }}
</p-tabPanel>
</p-tabView>
编辑:添加了更改标签的代码。我只需将新元素推送到pieceCollection
并更新selectedTabIndex
的值:
addNewPiece() {
if (this.canCreateNewPiece){
this.pieceCollection.push(new RequestPiece());
this.selectedTabIndex = this.pieceCollection.length;
}
}
答案 0 :(得分:2)
您可以在addNewPiece
中更改以下两项内容:
this.pieceCollection.length - 1
而不是this.pieceCollection.length
ExpressionChangedAfterItHasBeenCheckedError
方法1 - 异步设置索引
addNewPiece() {
if (this.canCreateNewPiece){
this.pieceCollection.push(new RequestPiece());
setTimeout(() => {
this.selectedTabIndex = this.pieceCollection.length - 1;
}, 0);
}
}
方法2 - 在设置索引之前触发变更检测
constructor(private changeDetectorRef: ChangeDetectorRef, ...) { }
addNewPiece() {
if (this.canCreateNewPiece){
this.pieceCollection.push(new RequestPiece());
this.changeDetectorRef.detectChanges();
this.selectedTabIndex = this.pieceCollection.length - 1;
}
}