Angular2在for循环中加载动态内容/html

2023-11-26

我有一个 json 数组,它可以包含我想要加载的组件的组件或 html 选择器。我正在尝试在 for 循环中加载这些数据。当我尝试插入值 {{d.html}} 时,它显示为计划文本。当我使用下面的innerHTML方法并检查dom时,我在那里看到html,但它并不表现为自定义组件(dom将只包含而不是初始化它并用组件模板替换它。

我已经查看了动态内容加载器,但看起来不合适。这是在 for 循环中,因此无法使用模板语法,因此 loadIntoLocation 对我不起作用。也不确定如果组件有任何输入它将如何工作。

<div *ngFor="#d of dtabs" class="tab-pane" id="tab-{{d.component}}">
  <div [innerHTML]="d.html"></div>
</div>

我也在寻找一种方法来做到这一点。我看到了 @guyoung 的答案并基于此构建了一些东西。但后来我意识到DynamicComponentLoader.loadIntoLocation()在上一个版本中不再存在,并且DynamicComponentLoader已被弃用。

我阅读了一些文档和帖子,并创建了一个运行良好的新指令。查看:

import {
  Component,
  ComponentResolver,
  Directive,
  ViewContainerRef,
  Input,
  Injector,
  ApplicationRef
} from "@angular/core";

/**

  This component render an HTML code with inner directives on it.
  The @Input innerContent receives an array argument, the first array element
  is the code to be parsed. The second index is an array of Components that
  contains the directives present in the code.

  Example:

  <div [innerContent]="[
    'Go to <a [routerLink]="[Home]">Home page</a>',
    [RouterLink]
  ]">

**/
@Directive({
  selector: '[innerContent]'
})
export class InnerContent {

  @Input()
  set innerContent(content){
    this.renderTemplate(
      content[0],
      content[1]
    )
  }

  constructor(
    private elementRef: ViewContainerRef,
    private injector: Injector,
    private app: ApplicationRef,
    private resolver:ComponentResolver){
  }

  public renderTemplate(template, directives) {
    let dynComponent = this.toComponent(template, directives)
    this.resolver.resolveComponent(
      dynComponent
    ).then(factory => {
      let component = factory.create(
        this.injector, null, this.elementRef._element.nativeElement
      );

      (<any>this.app)._loadComponent(component);
      component.onDestroy(() => {
        (<any>this.app)._unloadComponent(component);
      });
      return component;
    });
  }

private toComponent(template, directives = []) {
  @Component({
    selector: 'gen-node',
    template: template,
    directives: directives
  })
  class DynComponent {}
    return DynComponent;
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular2在for循环中加载动态内容/html 的相关文章

随机推荐