Home > database >  Angular HTML: ng-content in ngSwitch
Angular HTML: ng-content in ngSwitch

Time:11-15

The ng-content doesn't work in Angular ngSwitch case. ng-content for the code below only work in default case but not in other case.

<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>

But if code below works again. I have no idea how to make the ng-content work in switchCase. Is there any way to allow multiple ng-content so that the code below will works.

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

CodePudding user response:

The question to your answer can be found here: https://angular.io/guide/content-projection#conditional-content-projection

The actual problem is described pretty good there:

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.

The solution is also described pretty good:

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.

This means you should use the following code to achieve what you are trying to:

<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>

  • Related