Issue
I am trying to display a template based on an array of classes. I am not sure how I would do something like this.
I have created two templates that would be referenced by a for loop. The template looks something like this:
<ul>
<li *ngFor="let item of items">
<!-- Show one of the templates here -->
</li>
</ul>
<ng-template #buttonTemplate>
<button>Some Text</button>
</ng-template>
<ng-template #linkTemplate>
<a href="">Some Text</a>
</ng-template>
Next I created a javascript component that looks something like this:
@Component({ /* Options */ })
export class MyComponent {
constructor() {
this.items = [
new ButtonClass(),
new LinkClass(),
new ButtonClass()
]
}
}
Now, how would I use #buttonTemplate
when the item is instanceof ButtonClass
and use #linkTemplate
when the item is instanceof LinkClass
?
Solution
What I ended up doing is using @ViewChild
, this allowed me to return a template to ngTemplateOutlet
.
So my html didn't change much except for the new ng-template
in the for
loop.
<ul>
<li *ngFor="let item of items">
<ng-template *ngTemplateOutlet="item | getTemplate : buttonTemplate : linkTemplate; context: {$implicit: {model: item, /* other properties */}}">
</li>
</ul>
<ng-template #buttonTemplate let-item>
<button>{{item.model.text}}</button>
</ng-template>
<ng-template #linkTemplate let-item>
<a href="{{item.model.endpoint}}">{{item.model.text}}</a>
</ng-template>
In my JavaScript/TypeScript I added a @ViewChild
, and a function that takes an item and tests the reference and returns the proper TemplateRef
.
@Component({ /* Options */ })
export class MyComponent {
@ViewChild('buttonTemplate', { static: true })
public buttonTemplate
@ViewChild('linkTemplate', { static: true })
public linkTemplate
public items = [
new ButtonClass(),
new LinkClass(),
new ButtonClass()
]
getTemplate(item) {
if(item instanceof ButtonClass) return this.buttonTemplate
if(item instanceof LinkClass) return this.linkTemplate
}
}
Answered By - Get Off My Lawn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.