ngTemplateOutlet with dynamic value

后端 未结 2 1121
温柔的废话
温柔的废话 2020-12-16 17:26

I\'m using ngTemplateOutlet with dynamic value.


    

        
2条回答
  •  长情又很酷
    2020-12-16 17:53

    • Render template refs by passing dynamic values to ngTemplateOutlet Directive
    • use Attribute binding to pass reference of templateRef stored in templateRefs array

    .ts file

    export class RenderTemplateRefsInNgTemplateOutletDirective {
      @ViewChild('one', { static: false }) one:TemplateRef;
      @ViewChild('two', { static: false }) two:TemplateRef;
      @ViewChild('three', { static: false }) three:TemplateRef;
    
      templateRefs: Array> = [];
    
      config: any = {
        'one': true,
        'two': false,
        'three': true,
      }
    
      objectKeys = Object.keys;
    
     ngAfterViewInit() {
      const values = Object.keys(this.config).filter(key => this.config[key]);
      values.forEach(key =>{
        this.templateRefs.push(this[key]); // accessing **this** component ViewChild 
                                          // with same **name** defined as `key` in forEach
      })
     }
    }
    
    

    .html

    
        
     
     
     
     

    Hello One

    Hello Two

    Hello Three

提交回复
热议问题