简体   繁体   English

ngFor 中的渲染组件

[英]render component in ngFor

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.在循环中,我想呈现WeightComponent ,但它只是将function WeightComponent()呈现为文本。

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?我看到了使用[innerHTML] 如何在 Angular 2 中通过 ng-for 将 HTML 字符串转换为真正的 HTML 元素的建议? 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>

There is a buil-in NgComponentOutlet directive that will help you with your task.有一个内置的NgComponentOutlet指令可以帮助您完成任务。

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:您需要做的就是将这些组件添加到NgModuleComponent entryComponents数组中,然后简单地使用它,如下所示:

ts ts

steps: [
  {
    label: 'label',
    component: WeightComponent,
  },
  {
    label: 'label',
    component: RecommendedComponent,
  },
  {
    label: 'label',
    component: WeightComponent,
  },
]

html html

<ng-template [ngComponentOutlet]="step.component"></ng-template>

Ng-run Example吴运行示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM