How can I have dynamic templateUrl for Angular2 Component?

前端 未结 1 1682
不知归路
不知归路 2020-12-21 05:31

I wanted to load component templateUrl based on value passed from parent component. I know tt can be pass through property binding to component by

相关标签:
1条回答
  • 2020-12-21 06:16

    Been struggling with something similar, but unfortunately you can't do this. Component templates are compiled at runtime. So, basically, I would make a component that compiles other child components (which I actually did)

    DynamicComponentLoader is beign deprecated. You need to use the ComponentResolver class to load other components inside the main one, like so:

    function makeComponent( selector, template, ...more )
    {
      @Component({ selector: selector, template: template })
      class FakeComponent {}
      return FakeComponent;
    }
    
    @Component({ ... })
    export class MainCmp implements OnInit
    {
      // place to insert
      @ViewChild('viewChild', {read: ViewContainerRef}) viewChild: ViewContainerRef;
    
      constructor(private compiler: ComponentResolver){}
      // or OnChanges, or event binding.. should work
    
      ngOnInit()
      {
        // decide on your custom logic here, get you @Input, whatever...
    
        // and you can actually make some custom dynamic component...
        let childCmp = makeComponent( custom, stuff, here );
    
        // compile then insert in your location, defined by viewChild
        this.compiler.resolveComponent( childCmp )
          .then( (compFactory:ComponentFactory) => this.viewChild.createComponent(compFactory) )
      }
    }
    
    0 讨论(0)
提交回复
热议问题