How to use variable to define templateUrl in Angular2

后端 未结 1 1064
庸人自扰
庸人自扰 2020-11-29 09:38

I want the component to set the templateUrl with a variable, but it doesn\'t work.

@Component({
    selector: \'article\',
    templateUrl: \'{{         


        
相关标签:
1条回答
  • 2020-11-29 10:19

    I think you should use dynamic component loading to do that.

    Let's say we have a json file:

    {
        "title": "My first article",
        "html": "app/articles/first.html"
    }
    

    We might create HtmlOutlet directive that will create component dynamicallу with desired templateUrl:

    @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(()=>...);;
        });
      }
    }
    

    And then use it like:

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

    Where html is path to article html

    See more details in this Plunkr

    0 讨论(0)
提交回复
热议问题