gpt4 book ai didi

html - Angular HTML : ng-content in ngSwitch

转载 作者:行者123 更新时间:2023-12-03 08:00:33 26 4
gpt4 key购买 nike

ng-content 在 Angular ngSwitch 情况下不起作用。下面代码的 ng-content 仅在默认情况下有效,在其他情况下无效。

<ng-container [ngSwitch]="variant">
<button *ngSwitchCase="variantType.SUCCESS">
<ng-content></ng-content>
</button>
<button *ngSwitchCase="variantType.WARNING">
<ng-content></ng-content>
</button>
<button *ngSwitchCase="variantType.ERROR">
<ng-content></ng-content>
</button>
<button *ngSwitchDefault>
<ng-content></ng-content>
</button>
</ng-container>

但是如果下面的代码再次有效。我不知道如何使 ng-content 在 switchCase 中工作。有没有办法允许多个 ng-content 以便下面的代码可以工作。

<ng-container [ngSwitch]="variant">
<button *ngSwitchCase="variantType.SUCCESS">
<ng-content></ng-content>
</button>
</ng-container>

最佳答案

您可以在这里找到问题的答案:https://angular.io/guide/content-projection#conditional-content-projection

那里对实际问题的描述非常好:

Using an element in these cases is not recommended, because when the consumer of a component supplies the content, that content is always initialized, even if the component does not define an element or if that element is inside of an ngIf statement.With an element, you can have your component explicitly render content based on any condition you want, as many times as you want. Angular will not initialize the content of an element until that element is explicitly rendered.

解决方案也描述得很好:

If your component needs to conditionally render content, or render content multiple times, you should configure that component to accept an element that contains the content you want to conditionally render.

这意味着您应该使用以下代码来实现您想要的目标:

<ng-container [ngSwitch]="variant">
<button *ngSwitchCase="variantType.SUCCESS">
<ng-container [ngTemplateOutlet]="content"></ng-container>
</button>
<button *ngSwitchCase="variantType.WARNING">
<ng-container [ngTemplateOutlet]="content"></ng-container>
</button>
<button *ngSwitchCase="variantType.ERROR">
<ng-container [ngTemplateOutlet]="content"></ng-container>
</button>
<button *ngSwitchDefault>
<ng-container [ngTemplateOutlet]="content"></ng-container>
</button>
</ng-container>

<ng-template #content>
<ng-content></ng-content>
</ng-template>

关于html - Angular HTML : ng-content in ngSwitch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74440969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com