noobie
noobie

Reputation: 27

Dynamic template outlet Angular

I am trying to make a dynamic ngTempateOutlet.
I tried as follows:

<ng-container *ngFor="let action of actions">
    <ng-container *ngTemplateOutlet="action"; context="{item}"></ng-container>
</ng-container>
<ng-template #DELETE let-item="item">delete</ng-template>
<ng-template #MODIFY let-item="item">modify</ng-template>

Where actions is ["DELETE", "MODIFY"].

It seems that action inside the *ngFor doesn't result in DELETE and MODIFY, because if I manually insert the values the templates are displayed, otherwise they aren't.

I would avoid doing manual checking in order to keep it dynamic (es:)

<ng-container *ngFor="let action of actions">
    <ng-container *ngTemplateOutlet="action === 'delete' ? 'DELETE' : 'MODIFY'"; context="{item}"></ng-container>
</ng-container>

Upvotes: 0

Views: 343

Answers (1)

Erickson Ferreira
Erickson Ferreira

Reputation: 24

It seems that you are trying to render different models dynamically using *ngTemplateOutlet based on an array of ações. No, it seems that the action variable inside the *ngFor loop is not resolving the string values "DELETE" and "MODIFY".

One possible reason for this could be that the values in the matrix of ações are not all in capital letters, but the model references are. In my example, model references are defined as #DELETE and #MODIFY. Therefore, you may try to alter the values in the action matrix for capital letters to correspond to the model references, like so:

<ng-container *ngFor="let action of actions">
    <ng-container *ngTemplateOutlet="action.toUpperCase()"; context="{item}"></ng-container>
</ng-container>

<ng-template #DELETE let-item="item">delete</ng-template>
<ng-template #MODIFY let-item="item">modify</ng-template>

Upvotes: -3

Related Questions