ngFor 中的渲染组件

Ron*_*nie 5 angular

我正在循环对象数组并在对象内部指定要加载的组件。例如,循环中的一项是

{
  label: 'Patient\'s Weight',
  subtitle: '',
  component: WeightComponent,
},
Run Code Online (Sandbox Code Playgroud)

在循环中我想渲染WeightComponent,但它只是渲染function WeightComponent()为文本。

我知道我这样做是错误的,但我不确定正确的方法是什么。我也尝试过

{
  label: 'Patient\'s Weight',
  subtitle: '',
  component: '<app-weight></app-weight>',
},
Run Code Online (Sandbox Code Playgroud)

但这也只是呈现为文本。我需要使用渲染服务类型吗?我看到了使用[innerHTML] How to translate HTML string to real HTML element by ng-for in Angular 2? 的建议。但他们说这条路线容易受到攻击。

目前正在这样做,这不太理想

<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>
Run Code Online (Sandbox Code Playgroud)

yur*_*zui 6

有一个内置的NgComponentOutlet指令可以帮助您完成任务。

您需要做的就是将这些组件添加到您的orentryComponents数组中,然后简单地使用它,如下所示:NgModuleComponent

ts

steps: [
  {
    label: 'label',
    component: WeightComponent,
  },
  {
    label: 'label',
    component: RecommendedComponent,
  },
  {
    label: 'label',
    component: WeightComponent,
  },
]
Run Code Online (Sandbox Code Playgroud)

html

<ng-template [ngComponentOutlet]="step.component"></ng-template>
Run Code Online (Sandbox Code Playgroud)

NG 运行示例