【问题标题】:render component in ngFor在 ngFor 中渲染组件
【发布时间】:2018-12-22 04:08:17
【问题描述】:

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

{
  label: 'Patient\'s Weight',
  subtitle: '',
  component: WeightComponent,
},

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

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

{
  label: 'Patient\'s Weight',
  subtitle: '',
  component: '<app-weight></app-weight>',
},

但这也只是呈现为文本。我需要使用渲染服务类型的东西吗?我看到了使用 [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>

【问题讨论】:

    标签: angular


    【解决方案1】:

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

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

    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

    【讨论】:

    • 出现了另一个问题。我通过@ViewChild(WeightComponent) weightComponent; 使用this.weightComponent.myFunction() 调用组件上的函数,这似乎已经停止工作。我尝试用WeightComponent.myFunction() 替换它,但它说该功能不存在。我需要实现某种类型的 onReady 吗?
    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多