在tabPanel上使用* ngFor时,primeNG以编程方式更改选项卡

时间:2018-03-30 17:50:57

标签: angular primeng

每当用户创建新标签页时,我都会尝试以编程方式更改为下一个标签。但是,我无法让它发挥作用。我看到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;
    }
}

1 个答案:

答案 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;
    }
}