ngFor中的渲染组件 [英] render component in ngFor

查看:178
本文介绍了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,
},

在循环中,我想呈现WeightComponent,但是它只是将function 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>',
},

但这也只是呈现为文本.我需要使用渲染服务类型的东西吗?我看到了使用[innerHTML]

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.

当前这样做不理想

<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.

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

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运行示例

Ng-run Example

这篇关于ngFor中的渲染组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆