2017-05-05 2 views
0

Ich dachte über die Schaffung kleiner Komponente in Angular, die tun wird, was <ng-include> in angularJS tut.Wie kann ich TemplateUrl während des Erstellens einer Instanz von Komponente nach Code dynamisch festlegen?

Zuerst muss ich Komponente eine Vorlage oder templateUrl zum Kompilieren geben? Was, wenn es etwas ist, das ich nur in der Laufzeit kenne?

@Component({ 
    selector: 'my-template', 
    // templateUrl: '', //won't render, must give it something? 
}) 
export class MyTemplate { 

@Input() templateURL: string; 

    constructor() { 
    console.log("template component was created!"); 
    } 

} 

Ich möchte Instanz dieser Komponente in Code erstellen und geben Sie ihre VorlageUrl. Etwas wie das:

var factory = this.resolver.resolveComponentFactory(MyTemplate); 
factory.templateUrl = // Is that possible? 

Kann es irgendwie getan werden? Das TemplateUrl ist etwas, das von @input kommt Wie in Code ich Instanz der Komponente erstellen und geben Sie ihre Eingabe?

Antwort

0

Ich denke, Sie sollten dynamische Komponente laden, um das zu tun.

Wir könnten HtmlOutlet Richtlinie erstellen, die Komponente dynamicallу mit gewünschten templateUrl schaffen:

@Directive({ 
    selector: 'html-outlet' 
}) 
export class HtmlOutlet { 
    @Input() html: string; 

    constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {} 

    ngOnChanges() { 
    const html = this.html; 
    if (!html) return; 

    @Component({ 
     selector: 'dynamic-comp', 
     templateUrl: html 
    }) 
    class DynamicHtmlComponent { }; 

    @NgModule({ 
     imports: [CommonModule], 
     declarations: [DynamicHtmlComponent] 
    }) 
    class DynamicHtmlModule {} 

    this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule) 
     .then(factory => { 
     const compFactory = factory.componentFactories 
       .find(x => x.componentType === DynamicHtmlComponent); 
     const cmpRef = this.vcRef.createComponent(compFactory, 0); 
     cmpRef.instance.prop = 'test'; 
     cmpRef.instance.outputChange.subscribe(()=>...); 
    }); 
    } 
} 

Und es dann gerne verwenden:

<html-outlet [html]="article?.html"> 

Wo html ist Pfad zu article.html

Verwandte Themen