问题描述
我有一个app-document-form-node
组件,它可以递归地构建组件。
组件app-document-form-node:
<ng-container *ngIf="block.type === fielType.Block">
<app-adresat-list *ngIf="block.tag === 'ADRESATS'" [list]="block?.children"></app-adresat-list>
<app-word-settings *ngIf="block.tag === 'WORD_SETTINGS'" [element]="block"></app-word-settings>
<app-parameters *ngIf="block.tag === 'PARAMETERS'" [element]="block"></app-parameters>
<app-document-parameters *ngIf="block.tag === 'GENERICPARAMETERS'" [element]="block"></app-document-parameters>
</ng-container>
<!----->
<ng-container *ngIf="block.type === fielType.Field">
<app-field [ismultisignator]="properties?.ismultisignator" [fieldDefinition]="block" (onSelected)="onFieldSelected($event)"></app-field>
</ng-container>
<!----->
<ng-container *ngIf="block.type === fielType.Table">
<app-postaddress *ngIf="block.tag === 'TAG_ADDR'" [element]="block"></app-postaddress>
</ng-container>
<!--------------->
<div class="children" *ngIf="block?.children && block.children.length">
<ng-template ngFor let-child [ngForOf]="block.children">
<app-document-form-node [block]="child" [properties]="properties"></app-document-form-node>
</ng-template>
</div>
问题在<ng-container *ngIf="block.type === fielType.Block"></ng-container>
部分。
发生这种情况时,应将所有子组件放置在组件<app-adresat-list
,<app-word-settings>
,<app-parameters>
,app-document-parameters
中,以防block
具有{{1} }。
现在它可以工作了,但是在上述所有组件之后:
children
作为<div class="children" *ngIf="block?.children && block.children.length"></div>
的结果,它渲染了一个特定的组件,然后在外面渲染了他的孩子。但是,如果存在子代,则应将其呈现在具体组件内部。
如何解决?
我的主要作用域是递归显示组件,但根据条件if block.type === fielType.Block
显示不同的组件。
作为解决方案:
我可以在*ngIf="block.tag
,<app-document-form-node>
,<app-adresat-list
,<app-word-settings>
的模板中添加<app-parameters>
,但是会引起循环依赖组件错误。
另一个假设是在每个组件中使用app-document-parameters
参考和投影:
<ng-template #children>
上面的代码有效,但是以错误的顺序渲染组件
解决方法
如果各种*ngIf="block.type === fielType.Block"
中都有孩子,则只需在第一个<app-document-form-node [block]="block.children"></app-document-form-node>
的末尾添加ng-container
。
<ng-container *ngIf="block.type === fielType.Block">
<app-adresat-list *ngIf="block.tag === 'ADRESATS'" [list]="block?.children"></app-adresat-list>
<app-word-settings *ngIf="block.tag === 'WORD_SETTINGS'" [element]="block"></app-word-settings>
<app-parameters *ngIf="block.tag === 'PARAMETERS'" [element]="block"></app-parameters>
<app-document-parameters *ngIf="block.tag === 'GENERICPARAMETERS'" [element]="block"></app-document-parameters>
<app-document-form-node [block]="block.children"></app-document-form-node>
</ng-container>