简体   繁体   中英

Angular - Create HTML Elements and Angular Components dynamically

I am currently working on an Angular 10 project where I have to add native HTML-elements like div, table, p, h1 to the DOM (this could be achieved in Angular with the DomSanitizer) from the TypeScript class. But I also want to create an Angular component inside an created div.

Because creating just one component is easy with the ComponentFactoryResolver.

For example, this should be created from Typescript dynamically:

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

How can I achieve this? Kind regards, Steve

I think is this what you're looking for:

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

You don't need <div> unless you use him for style or other thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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