2017-11-06 9 views

答えて

2

:) ありがとう:Angular 2/4 component with dynamic template or templateUrl

公式ソース:

import { 
    Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef, 
    ViewContainerRef, AfterViewInit, OnInit 
} from '@angular/core'; 


@Component({ 
    selector: 'bancaComponent', 
    template: ` 
    <ng-container #dynamicTemplate></ng-container> 
    ` 
    // or with a templateUrl 
}) 
export class BancaComponent implements AfterViewInit, OnInit { 
    @ViewChild('dynamicTemplate', {read: ViewContainerRef}) dynamicTemplate; 

    constructor(private _compiler: Compiler, 
       private _injector: Injector, 
       private _m: NgModuleRef<any>) { 
    } 

    ngAfterViewInit() { 
    let myTemplateUrl = './file.component.html'; 

    if (MYCONDITION === MAEXPECTATION) { 
     myTemplateUrl = './another-template.component.html'; 
    } 

    const tmpCmp = Component({ 
     moduleId: module.id, templateUrl: myTemplateUrl 
    })(class { 
    }); 
    const tmpModule = NgModule({declarations: [tmpCmp]})(class { 
    }); 

    this._compiler.compileModuleAndAllComponentsAsync(tmpModule) 
     .then((factories) => { 
     const f = factories.componentFactories[0]; 
     const cmpRef = f.create(this._injector, [], null, this._m); 
     cmpRef.instance.name = 'dynamic'; 
     this.dynamicTemplate.insert(cmpRef.hostView); 
     }); 
    } 
} 

からインスピレーションを受けhttps://angular.io/guide/dynamic-component-loader

+0

おかげで、しかし、ここではそれがで編集しています変数 – Dell

+0

で編集しません。変数と条件例;) – Boulboulouboule

+0

それは仲間ではない、それは私にエラーを与える – Dell

関連する問題