繁体   English   中英

Angular - 动态加载包含 angular 标记的 html

[英]Angular - Dynamically load html that includes angular markups

在 Angular 9+ 中,我可以成功地将字符串转换为 html,然后使用 innerHtml 和 bypassSecurityTrustHtml() 加载该 html。

我的问题是还可以动态加载/渲染转换后的 html 以包含和识别 angular/javascript 标记语言,例如 *ngIf、句柄栏和点击事件。

下面是到目前为止尝试的代码和 stackblitz,但正如您所见,它无法识别标记。

https://stackblitz.com/edit/dynamic-angular?file=app/app.component.ts

export class AppComponent implements OnInit {
  text: string = "Hello world";
  content: any;
  constructor(private domSantizer: DomSanitizer) {}

  ngOnInit() {
    let body: any =
      '<div>{{text}}<div><br><button (click)="test()">Test</button>';
    this.content = this.domSantizer.bypassSecurityTrustHtml(body);
  }

  test() {
    alert("It works");
  }
}

Html

<div [innerHTML]="content"></div>

我研究并尝试了许多解决方案。 我的研究和试验结果如下。

html

<div #container></div>

typescript 侧如下

export class AppComponent implements OnInit {
  @ViewChild("container", { read: ViewContainerRef })
  container: ViewContainerRef;
  constructor(private compiler: Compiler) {}
  text: string = "asdasd";
  ngOnInit() {
    this.addComponent(
      `<div>{{text}}<div><br><button (click)="test()">Test</button>
       `,
      {
        text: "Hello word",
        test: function() {
          alert("It's work");
        }
      }
    );
  }

  private addComponent(template: string, properties?: any = {}) {
    @Component({ template })
    class TemplateComponent {}

    @NgModule({ declarations: [TemplateComponent] })
    class TemplateModule {}

    const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
    const factory = mod.componentFactories.find(
      comp => comp.componentType === TemplateComponent
    );
    const component = this.container.createComponent(factory);
    Object.assign(component.instance, properties);
    // If properties are changed at a later stage, the change detection
    // may need to be triggered manually:
    // component.changeDetectorRef.detectChanges();
  }

演示

我审查过的一些帖子

编译动态组件

角度 html 绑定

我认为这是最有意义的:)

暂无
暂无

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

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