我正在构建一个角的头组件,并希望根据输入inputTwoRows
是否设置为true/false
来显示DOM结构中不同位置的导航。nav通过内容投影- ng-content
添加到标题的模板中。我尝试在模板中的不同位置将2 ng-content
包装在ng-templates
中,并添加了ngIf
以有条件地显示它们。然而,模板试图显示相同的预计内容。正如您将在Stackblitz链接中看到的那样,如果在ng-content
上显示[twoRows]="true"
,则只显示第一个c-header
。下面是header.component.html
的代码
<header>
<div>logo</div>
<ng-template [ngIf]="inputTwoRows">
<p>Two Rows</p>
<ng-content select="c-header-nav"></ng-content>
</ng-template>
<div>utils</div>
<ng-template [ngIf]="!inputTwoRows">
<p>One Row</p>
<ng-content select="c-header-nav"></ng-content>
</ng-template>
</header>
如果两个ng-template
中的内容不是ng-content
,则这个逻辑工作得很好。有什么办法可以达到我原来的目标吗?
https://stackblitz.com/edit/angular-ivy-xfr7hs?file=src/app/components/header/header.component.html
谢谢
詹姆斯
发布于 2022-07-27 12:00:44
最后,我定义了一个封装在一个<ng-content>
中的<ng-template>
。然后,我将<ng-containers>
放在DOM中需要它们的位置。外部<ng-containers>
处理条件逻辑,如果需要,内部<ng-containers>
引用<ng-template>
:
<header>
<div>logo</div>
<ng-container *ngIf="!twoRows">
<ng-container *ngTemplateOutlet="headerNavTemplate"></ng-container>
</ng-container>
<div>utils</div>
<ng-container *ngIf="twoRows">
<ng-container *ngTemplateOutlet="headerNavTemplate"></ng-container>
</ng-container>
<ng-template #headerNavTemplate>
<ng-content select="c-header-nav"></ng-content>
</ng-template>
</header>
发布于 2022-07-27 10:38:25
这是因为ng内容发生在构建时。在实例化宿主组件时实例化,这也意味着在编译代码时,角编译器将创建规则和相关的JS代码。运行时对以后的行为没有影响.在更新组件时,它不会更改。
https://stackoverflow.com/questions/73142618
复制