我有以下带有开关的模板:
<ng-container [ngSwitch]="block.type">
<ng-container *ngSwitchCase="'block'">
<div class="requestDocumentBlock">
<div>
<ng-container *ngTemplateOutlet="children; context: { block: block }"></ng-container>
</div>
</div>
</ng-container>
<!-- Field --->
<ng-container *ngSwitchCase="'field'">
<app-request-document-field [fieldDefinition]="block"></app-request-document-field>
</ng-container>
<!-- Custom --->
<ng-container *ngSwitchDefault>
<app-request-document-field
[fieldDefinition]="block"
*ngFor="let block of documentCustomBlock?.getVisibleControls()"
></app-request-document-field>
<button (click)="setDocument()" type="button" class="btn btn-primary">Задать документ</button>
</ng-container>
</ng-container>
所以,问题出在这部分代码:
<app-request-document-field
[fieldDefinition]="block"
*ngFor="let block of documentCustomBlock?.getVisibleControls()"
></app-request-document-field>
默认情况下,documentCustomBlock?.getVisibleControls()
是空数组。当数据到来时,它将开始无限渲染整个模板。
我不明白为什么?
更新:
组件为:
public documentCustomBlock: DocumentCustomBlock;
this.dialog
.open(DialogLoadDocumentComponent, dialogConfig)
.afterClosed()
.subscribe((documentCustomBlock: DocumentCustomBlock) => {
this.documentCustomBlock = documentCustomBlock;
this.changeDetection.detectChanges();
});
模板为:
<app-request-document-field
[fieldDefinition]="block"
*ngFor="let block of documentCustomBlock?.getVisibleControls()"></app-request-document-field>
答案 0 :(得分:0)
可能的答案:
这将尝试仅获取一个可观察到的发射,它将更新数据
public documentCustomBlock: DocumentCustomBlock;
this.dialog
.open(DialogLoadDocumentComponent, dialogConfig)
.afterClosed()
.pipe(
take(1)
)
.subscribe((documentCustomBlock: DocumentCustomBlock) => {
this.documentCustomBlock = documentCustomBlock;
this.changeDetection.detectChanges();
});
或
这将使用异步管道,该管道将自动解决
public documentCustomBlock: DocumentCustomBlock = this.dialog
.open(DialogLoadDocumentComponent, dialogConfig)
.afterClosed();
<app-request-document-field
[fieldDefinition]="block"
*ngFor="let block of documentCustomBlock?.getVisibleControls() | async"
></app-request-document-field>