How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

后端 未结 15 1884
忘掉有多难
忘掉有多难 2020-11-21 05:14

I want to dynamically create a template. This should be used to build a ComponentType at runtime and place (even replace) it somewhere inside of the ho

15条回答
  •  长情又很酷
    2020-11-21 06:00

    For this particular case looks like using a directive to dynamically create the component would be a better option. Example:

    In the HTML where you want to create the component

    
    

    I would approach and design the directive in the following way.

    const components: {[type: string]: Type} = {
        text : TextEditorComponent,
        numeric: NumericComponent,
        string: StringEditorComponent,
        date: DateComponent,
        ........
        .........
    };
    
    @Directive({
        selector: '[dynamicComponentDirective]'
    })
    export class DynamicComponentDirective implements YourConfig, OnChanges, OnInit {
        @Input() yourConfig: Define your config here //;
        component: ComponentRef;
    
        constructor(
            private resolver: ComponentFactoryResolver,
            private container: ViewContainerRef
        ) {}
    
        ngOnChanges() {
            if (this.component) {
                this.component.instance.config = this.config;
                // config is your config, what evermeta data you want to pass to the component created.
            }
        }
    
        ngOnInit() {
            if (!components[this.config.type]) {
                const supportedTypes = Object.keys(components).join(', ');
                console.error(`Trying to use an unsupported type ${this.config.type} Supported types: ${supportedTypes}`);
            }
    
            const component = this.resolver.resolveComponentFactory(components[this.config.type]);
            this.component = this.container.createComponent(component);
            this.component.instance.config = this.config;
        }
    }
    

    So in your components text, string, date, whatever - whatever the config you have been passing in the HTML in the ng-container element would be available.

    The config, yourConfig, can be the same and define your metadata.

    Depending on your config or input type the directive should act accordingly and from the supported types, it would render the appropriate component. If not it will log an error.

提交回复
热议问题