Reputation: 4262
I have a switch case with duplicated html code so I want to reduce this by using ng-container
like below:
<div *ngSwitchCase="competences">
<ng-container *ngTemplateOutlet="commonOsiCatalogInfoContainer"></ng-container>
</div>
And here is the ng-template:
<ng-template #commonOsiCatalogInfoContainer>
<osi-catalog-info-container>
<div header>
{{ veld.titel }}
</div>
<div body>
<li *ngFor="let blok of veld.waarde">
<div class="s-margin-b">
<osi-li-h>{{ blok.toets_omschrijving }}</osi-li-h>
</div>
<ion-row *ngFor="let _veld of blok.velden" class="s-margin-b">
<ion-col col-auto class="work-form-title-col">
<osi-h4>{{_veld.titel}}</osi-h4>
<osi-li-body class="osi-black-87 d-block"><b>{{_veld.waarde}}</b></osi-li-body>
</ion-col>
</ion-row>
</li>
</div>
</osi-catalog-info-container>
</ng-template>
The only thing that differs is the osi-li-h
value in some cases it is blok.title
how can I make this osi-li-h
dynamic in the ng-template
?
Upvotes: 2
Views: 12122
Reputation: 818
You can attach a context object to ng-container and pass the value to your template.
As per docs:
You can attach a context object to the EmbeddedViewRef by setting [ngTemplateOutletContext]. [ngTemplateOutletContext] should be an object, the object's keys will be available for binding by the local template let declarations.
Inside your template, you have to do this:
<ng-container *ngTemplateOutlet="eng; context: myContext"></ng-container>
<ng-template #eng let-name><span>Hello {{name}}!</span></ng-template>
Upvotes: 0
Reputation: 161
You can pass a context to your ngTemplate like mentioned in this documentation https://angular.io/api/common/NgTemplateOutlet
You can supply your context in either of the two approches
<div *ngSwitchCase="Field.FIELD_NAME_COMPETENCES">
<ng-container *ngTemplateOutlet="commonOsiCatalogInfoContainer; context: contextExp"></ng-container>
</div>
or by using ngTemplate directly like
<div *ngSwitchCase="Field.FIELD_NAME_COMPETENCES">
<ng-template [ngTemplateOutlet]="commonOsiCatalogInfoContainer [ngTemplateOutletContext]="contextExp"></ng-template>
</div>
in both the above examples contextExp
is nothing but a JSON object.
Then you may use the passed on context properties directly inside your template like
<ng-template #commonOsiCatalogInfoContainer let-myIdentifier="JSON_PROPERTY">
<osi-catalog-info-container>
<div *ngIf="myIdentifier == 'something'"></div>
</osi-catalog-info-container>
</ng-template>
Upvotes: 3