Search code examples
angularangular-template

How do I add a attribute to a ng-template?


I have a search component with a ng-template derived from a directive TableHeaderDirective

@Directive({
    selector: '[appTableHeader]'
})
export class TableHeaderDirective {
    @Input() filter = 'click'; // pass desired event
    constructor(public tpl: TemplateRef<any>) { }
}

I have this working and the template setup. Now I want to add the filter Attribute like below:

<sym-search [search]="searchString" [data]="data">
    <ng-template appTableHeadersTemplate>
        <ng-template appTableHeader [filter]="'Username'">
            Username
        </ng-template>
        <ng-template appTableHeader filter="'FirstName'">
            First Name
        </ng-template>
        <ng-template appTableHeader filter="'LastName'">
            Last Name
        </ng-template>
    </ng-template>
</sym-search>

I later want this in the search component by getting the children for the templates

@ContentChildren(TableHeaderDirective, { read: TemplateRef })
tableHeaderItems: QueryList<TemplateRef<any>>;

and then looping to output th tags

<th *ngFor="let headerItem of tableHeaderItems; index as i;">
{{headerItem.filter}}
    <ng-container *ngTemplateOutlet="headerItem"></ng-container>
</th>

How can I get access to the [Filter] so that I can added it to the th tag?

Do I need to create a filterDirective and if so how do I access it on the search component?


Solution

  • Instead of reading template reference you can read directive reference. so that you can access directive template reference and input property inside your component.

    Try this

    component.ts

    @ContentChildren(TableHeaderDirective, { read: TableHeaderDirective }) tableHeaderItems: QueryList<TableHeaderDirective<any>>;
    

    Example

    component.html

    <th *ngFor="let headerItem of tableHeaderItems; index as i;">
       {{headerItem.filter}}
        <ng-container *ngTemplateOutlet="headerItem.tpl"></ng-container>
    </th>