我首先有一个看起来像这样的父/子组件
父母
<child-comp>
<div firstContent>This is my first content</div>
<div secondContent>This is my second content</div>
</child-comp>
孩子
<div redColourDirective>
<div>This is the template with directive applied</div>
<ng-content select="[firstContent]"></ng-content>
<ng-content select="[secondContent]"></ng-content>
</div>
...然后我希望指令redColourDirective是有条件的,所以模板变成了这样(主要是因为我不能有条件指令)
<ng-container *ngTemplateOutlet="withDirective() ? tmp1 : tmp2"> </ng-container>
<ng-template #tmp1>
<div redColourDirective>
<div>This is the template with directive applied</div>
<ng-content select="[firstContent]"></ng-content>
<ng-content select="[secondContent]"></ng-content>
</div>
</ng-template>
<ng-template #tmp2>
<div>
<div>This is the template WITHOUT directive applied</div>
<ng-content select="[firstContent]"></ng-content>
<ng-content select="[secondContent]"></ng-content>
</div>
</ng-template>
...其中withDirective()是作为输入的信号。现在,当 withDirective 从父组件设置为 true 时,firstContent、secondContent 会投射到子组件中,但当 withDirective 设置为 false 时则不会。我在这里做错了什么?
//works, ng-content visible
<child-comp [withDirective]="true">
<div firstContent>This is my first content</div>
<div secondContent>This is my second content</div>
</child-comp>
//fails, no ng-content visible
<child-comp [withDirective]="false">
<div firstContent>This is my first content</div>
<div secondContent>This is my second content</div>
</child-comp>
我尝试过的方法: Stackblitz 演示