Angular reusable template

后端 未结 1 1349
忘掉有多难
忘掉有多难 2021-02-10 09:55

Is it possible to write reusable ng-template? A lot of my components use exactly the same ng-template.
For example:



        
1条回答
  •  被撕碎了的回忆
    2021-02-10 10:21

    The problem is that ng-template has to be compiled. To understand why read Here is what you need to know about dynamic components in Angular.

    Now, a template can only be compiled as part of a component right now. So you need to define a component with this template and then you can get access to this template factory either using viewChild or a directive. With viewChild you depend on life-cycle hooks and change detection so I'd go with directive approach. Here is the pseudocode:

    @Component() {
       template: '...'
    }
    class NgTemplateProviderComponent {
       t: TemplateRef;
    
       register(t) {
          this.t = t;
       }
    }
    
    @Directive() {
       selector: 'requestor; 
    }
    class TemplateRequestor {
       constructor(t: TemplateRef, p: NgTemplateProviderComponent) {
          p.register(t);
       }
    }
    

    To learn more about this approach of using a directive to get templateRef read Here is how to get ViewContainerRef before @ViewChild query is evaluated.

    Then, you need to get access to the NgTemplateProviderComponent component factory, create its instance to get the templateRef:

    class SomeComponent {
       constructor(r: ComponentFactoryResolver, i: Injector) {
           const f = r.resolveComponentFactory(NgTemplateProviderComponent);
           const templateRef =f.create(i).instance.t;
       }
    }
    

    and only then you can use ngTemplateOutlet directive to render the template.

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