Angular Dynamic Component

Dynamic Component

  1. Use Directive
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    // create directive
    ng generate directive directives/DynamicChildLoader

    // Content in DynamicChildLoader

    import { Directive, ViewContainerRef } from '@angular/core';

    @Directive({
    selector: '[dynamicChildLoader]',
    })
    export class DynamicChildLoaderDirective {
    constructor(public viewContainerRef: ViewContainerRef) {}
    }

Usage in your ts file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@ViewChild(DynamicChildLoaderDirective, { static: true })
dynamicChild!: DynamicChildLoaderDirective;

ngOnInit(): void {
this.loadDynamicComponent();
}

private loadDynamicComponent() {
this.dynamicChild.viewContainerRef.createComponent(YourDynamicChildComponent);
}


// YourDynamicChildComponent has registed in moudle
@NgModule({
declarations: [MyExampleComponent, DynamicChildLoaderDirective],
imports: [CommonModule, ComponentsModule],
})

本文作者: 孟 虎
本文链接: https://menghu1994.github.io/blog/2023/10/Angular/Dynamic%20Components/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!