Laila Ali
Laila Ali

Reputation: 13

Add labels to each ng-template

I'm trying to add Labels or Names for each of my ng-template and then save that label in a property and I'm not sure how to do this.

I would like to do this because, I want each ng-template associated with the correct Label when the list of ng-templates is iterated over.

To Note: I am creating a reusable Tab component. The Tab component will hold the logic and the Parent component will hold the ng-templates since only the Parent knows what kind of templates it will need.

And each ng-template needs a tab label to go with it.

Tried: I have tried adding name = "Label 2" to the ng-template but I don't think that did anything.

 <ng-template #temp1 name="Label 2"> <p>this is template 2</p> </ng-template>

Goal: I want to fill my templates property with an object like this.

let templates = {tempLabel: 'Label 2', template: 'temp1'}

I already got the template: temp1 part, I just need the tempLabel: 'Label 2 part of the object.

Upvotes: 0

Views: 1460

Answers (1)

cezn
cezn

Reputation: 3055

You can create custom directive that will store label and template itself, like this:

@Directive({
  selector: '[appLabel]'
})
export class LabelDirective {
  constructor(public templateRef: TemplateRef<any>) { }
  @Input('appLabel') label = '';
}

And inject it into component:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChildren(LabelDirective) templates: QueryList<LabelDirective> 
}

Here's the AppComponent template:

<ng-template appLabel="label 1"></ng-template>
<ng-template appLabel="label 2"></ng-template>
<ng-template appLabel="label 3"></ng-template>

<ul>
    <li *ngFor="let t of templates">{{t.label}} - {{ t.templateRef }}</li>
</ul>

And here's the working example https://stackblitz.com/edit/angular-w8sd4y

Upvotes: 1

Related Questions