【问题标题】:Angular - Create HTML Elements and Angular Components dynamicallyAngular - 动态创建 HTML 元素和 Angular 组件
【发布时间】:2020-11-11 15:25:40
【问题描述】:

我目前正在开发一个 Angular 10 项目,我必须从 TypeScript 类中将 div、table、p、h1 等原生 HTML 元素添加到 DOM(这可以在 Angular 中使用 DomSanitizer 实现)。但我也想在创建的 div 中创建一个 Angular 组件。

因为使用 ComponentFactoryResolver 可以轻松创建一个组件。

例如,这应该从 Typescript 动态创建:

<div>
<my-component></my-component>
</div>

我怎样才能做到这一点? 亲切的问候, 史蒂夫

【问题讨论】:

    标签: html angular typescript web dynamically-generated


    【解决方案1】:

    我想这就是你要找的东西:

        import {Component} from '@angular/core';
        
        @Component({
          selector: 'example',
          templateUrl: '<my-component></my-component>',
          styleUrls: ['./example.component.scss']
        })
        export class ExampleComponent {
        }
    

    你不需要&lt;div&gt;,除非你把他用于风格或其他事情。

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2020-12-29
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      • 2017-09-10
      • 2019-01-07
      • 2017-02-24
      相关资源
      最近更新 更多