代码之家  ›  专栏  ›  技术社区  ›  Ka Tech

角度-动态加载包含角度标记的html

  •  0
  • Ka Tech  · 技术社区  · 4 年前

    在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>
    
    0 回复  |  直到 4 年前
        1
  •  2
  •   errorau    4 年前

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

    html

    <div #container></div>
    

    打印下面的脚本

    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();
      }
    

    demo

    我看过的一些帖子

    compile dynamic Component

    angular-html-binding

    I think it makes the most sense :)