Search code examples
angularangular-directiveangular6ng-template

Accessing each ng-template name using @ContentChildren()


I have written a component named my-component and added some ng-template inside, and named each with # like this:

<my-component>
    <ng-template #one>
        1st format
    </ng-template>
    <ng-template  #two>
        2nd template
    </ng-template>
    <ng-template  #three>
        3rd template
    </ng-template>
</my-component>

at the declaration of MyComponent, I used @ContentChildren(TemplateRef) to access these three templates.

Now I need to access the names of these templates (one, two, three) somehow inside MyComponent but I don't know how. Here is the code: sample code


Solution

  • I created a component which uses ng-templates and I struggled to find documentation about it. A bit of trial and error and I figured out how to use the @ContentChild

      @ContentChild('one') oneTemplate: TemplateRef<any>;
      @ContentChild('two') twoTemplate: TemplateRef<any>;
    

    and then in the UI html template of my-component you use them like this:

    <ng-container *ngTemplateOutlet="oneTemplate"></ng-container>
    <ng-container *ngTemplateOutlet="twoTemplate"></ng-container>
    

    The component usage would be like you described:

    <my-component>
        <ng-template #one>
            1st format
        </ng-template>
        <ng-template  #two>
            2nd template
        </ng-template>
    </my-component>
    

    Hope this helps and works for someone. Feedback appreciated.