Search code examples
angularng-container

Create Angular component that behaves like ng-container


How can an Angular component behave like <ng-container> in that only its content is found in the DOM finally. In particular, if itself is written with content, the content shall end up in the template's slots, e.g. Suppose the template basically is:

<my-toolbar>
  <ion-toolbar></ion-toolbar>
</my-toolbar>

and the HTML is like

<my-toolbar>
  <span>stuff</span>
</my-toolbar>

then the rendered DOM should be like

<ion-toolbar>
  <slot>#ref to span below<slot>
  <span>stuff</span>
</ion-toolbar>

i.e. the <my-toolbar> host element is gone. Is that at all possible?

Tried so far: Several similarly sounding questions have answers as to use an attribute selector like [my-toolbar] and then write <ion-toolbar my-toolbar> yet then angular complains that ion-toolbar matches more than one selector, I guess the default and [my-toobar].


Solution

  • Inside my-toolbar component template, you should add <ng-content></ng-content>

    my-toolbar.component.html

    <ion-toolbar>
    <ng-content></ng-content>
    <div>static div</div>
    </ion-toolbar>
    

    Usage:

    <my-toolbar>
    <span>some text</span>
    </my-toolbar>
    

    Result:

    <ion-toolbar>
    <span>some text</span>
    <div>static div</div>
    </ion-toolbar>