【问题标题】:How can I set templateUrl dynmically while creating an instance of component by code?如何在通过代码创建组件实例时动态设置 templateUrl?
【发布时间】:2017-10-03 15:51:42
【问题描述】:

我正在考虑在 Angular 中创建一个小组件,它可以完成 <ng-include> 在 angularJS 中所做的事情。

首先,我必须给组件一个模板或 templateUrl 来编译?如果我只能在运行时知道怎么办?

@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!");
  }

}

我想在代码中创建该组件的实例并给出它的 templateUrl。类似的东西:

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

可以以某种方式完成吗? templateUrl 将来自@input 如何在代码中创建组件实例并为其提供输入?

【问题讨论】:

    标签: angular angular2-directives angular2-components


    【解决方案1】:

    我认为你应该使用动态组件加载来做到这一点。

    我们可能会创建 HtmlOutlet 指令,该指令将使用所需的 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(()=>...);
        });
      }
    }
    

    然后像这样使用它:

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

    htmlarticle.html

    的路径

    【讨论】:

      猜你喜欢
      • 2015-09-26
      • 2015-04-25
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      相关资源
      最近更新 更多