5

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>
Ronnie
  • 11,138
  • 21
  • 78
  • 140

1 Answers1

6

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>

Ng-run Example

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • another question arose. I was calling functions on the component via `@ViewChild(WeightComponent) weightComponent;` using `this.weightComponent.myFunction()` and that seems to have stopped working. I tried replacing it with `WeightComponent.myFunction()` but it says that function does not exist. Do I need to implement some type of onReady thing? – Ronnie Dec 21 '18 at 20:23