首页 > 解决方案 > 在 html 页面中通过 typescript 打印 html 标签

问题描述

这是一个角度应用程序。我想在另一个组件中调用一个组件。所以,如果我这样写第一个组件来使用第二个组件的选择器调用第二个组件:

html:

<div>
    <app-nice-component></app-nice-component>
</div>

一切正常。

但是我有很多组件,如果我尝试从一个数组中做同样的事情,它不再是一个 HTML 标签,它变成一个字符串(我的第二个组件不再加载)

ts:

let x: string[] = [{<app-nice-component></app-nice-component>},{<app-nice2-component></app-nice2-component>}]

html:

<div>
    {{x[0]}}
</div>

那么在第二种情况下,我怎样才能使它成为一个 HTML 标签,而不是一个字符串呢?

标签: javascripthtmlangulartypescript

解决方案


我建议你阅读下一篇关于 Angular 中动态组件加载器的文档:https ://angular.io/guide/dynamic-component-loader

您需要动态加载组件。脚步:

  1. 创建一个指令来告诉您的 HTML 代码在哪里加载组件:

    @Directive({
        selector: '[myDirective]'
    })
    export class MyDirective {
        constructor(public viewContainerRef: ViewContainerRef) { }
    }
    
  2. 使用新指令将您的 HTML 设置到 ng-template 中,不要忘记在使用它的模块中添加指令。

    <div>
        Component loading:
        <ng-template myDirective></ng-template>
    </div>
    
  3. 创建一个动态加载的函数,需要导入所有你想使用的组件,在这个例子中我准备了3个组件并动态加载它们,你可以玩componentToLoad数组来动态加载更多或更少的组件。

    ngOnInit() {
    
        let componentToLoad : any[];
        componentToLoad = [ this.componentFactoryResolver.resolveComponentFactory(Component1Component), 
                            this.componentFactoryResolver.resolveComponentFactory(Component2Component),
                            this.componentFactoryResolver.resolveComponentFactory(Component3Component) ]
    
        const viewContainerRef = this.myDirective.viewContainerRef;
    
        componentToLoad.forEach( c => {
            viewContainerRef.createComponent(c);
        });
    }
    

推荐阅读