Reputation: 11198
I am looping over an object array and inside the object I want to specify a component to load. For example, one of the items in the loop is
{
label: 'Patient\'s Weight',
subtitle: '',
component: WeightComponent,
},
In the loop I want to render the WeightComponent
, but it just renders function WeightComponent()
as text.
I know I am doing this incorrectly, but I am not sure what the correct way is. I also tried
{
label: 'Patient\'s Weight',
subtitle: '',
component: '<app-weight></app-weight>',
},
but that too just renders as text. Is there a render service type thing I need to use? I seen suggestions to use [innerHTML]
How to translate HTML string to real HTML element by ng-for in Angular 2? but they say that route is open to attacks.
currently doing this which is less than ideal
<div *ngFor="let step of selectedDosing.steps; index as i" class="step" [attr.step]="i">
<ion-label class="step-title">
<span class="number">{{ i + 1 }}</span>
<span class="labels">
<div class="main-label">{{ step.label }}</div>
<div class="subtitle">{{ step.subtitle }}</div>
</span>
</ion-label>
<app-hepatic-impairment *ngIf="step.component == 'hepatic-impairment'"></app-hepatic-impairment>
<app-recommended *ngIf="step.component == 'recommended'"></app-recommended>
<app-weight *ngIf="step.component == 'weight'"></app-weight>
</div>
Upvotes: 5
Views: 2840
Reputation: 214047
There is a buil-in NgComponentOutlet directive that will help you with your task.
All you need to do is to add those components to entryComponents
array of your NgModule
or Component
and then simply use it as follows:
ts
steps: [
{
label: 'label',
component: WeightComponent,
},
{
label: 'label',
component: RecommendedComponent,
},
{
label: 'label',
component: WeightComponent,
},
]
html
<ng-template [ngComponentOutlet]="step.component"></ng-template>
Upvotes: 7