16 July 2020

Angular Runtime compilation - Dynamic Template From HTTP Call

Biên Dịch Thời Gian Thực Angular 

Template Động gọi HTTP hoặc mẫu HTML có sẵn.

MyComponent
2020
import {
    Component,
    OnInit
} from '@angular/core';
import {
    HttpClientModule
} from '@angular/common/http';

@Component({
    selector: 'mycomponent',
    template: '<strong>Loading</strong>'
})
export class MyComponent implements OnInit {

    constructor(private http: HttpClientModule) {}

    public ngOnInit(): void {
        this.http.get('https://myapiUrl').subscribe(data: any => {
            // Here data is HTML string, and I want to set it instead of the "<div>Hello World!</div>"
            // => compileTemplate(data);
        });
    }
}
RuntimeContentComponent
2020
@Component({
    selector: 'runtime-content',
    template: `<div #container></div>`
})
export class RuntimeContentComponent {

    @ViewChild('container', {
        read: ViewContainerRef
    }) container: ViewContainerRef;

    constructor(public componentRef: ComponentRef, private compiler: Compiler) {}

    /** 
     * Example: <div>layout..</div>
     * Input: Html
     * @param template */
    public compileTemplate(template) {

        let metadata = {
            selector: `runtime-component-sample`,
            template: template
        };

        let factory = this.createComponentFactorySync(this.compiler, metadata, null);

        if (this.componentRef) {
            this.componentRef.destroy();
            this.componentRef = null;
        }
        this.componentRef = this.container.createComponent(factory);
    }

    private createComponentFactorySync(compiler: Compiler, metadata: Component, componentClass: any): ComponentFactory < any > {
        const cmpClass = componentClass || class RuntimeComponent {
            name: string = 'Denys'
        };
        const decoratedCmp = Component(metadata)(cmpClass);

        @ NgModule({
            imports: [CommonModule],
            declarations: [decoratedCmp]
        })
        class RuntimeComponentModule {}

        let module: ModuleWithComponentFactories < any > = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);
        return module.componentFactories.find(f => f.componentType === decoratedCmp);
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang