html - Angular HTML : ng-content in ngSwitch

标签 html css angular

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/

相关文章:

javascript - Ajax 相关的文本字段和下拉菜单(PHP 和 Javascript)

html - 使用分块编码有什么好处?

javascript - IMG 周围的边框

html - 使用 Bootstrap 内联表单,我希望表单元素在移动设备上保持样式

javascript - 滚动后单击时下拉菜单消失

html - 内部CSS样式定义

javascript - 通过服务从 api 调用返回到组件的数据是一个对象,似乎需要成为 Angular 的数组

html - div~div和div :not(:first-of-type)?的区别

angular - 在 Angular 5 中验证后防止提交表单

Angular 阻塞(同步)http 调用