ngTemplateOutlet with dynamic value

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

I\'m using ngTemplateOutlet with dynamic value.


    

        
相关标签:
2条回答
  • 2020-12-16 17:53

    Add these to the components class

    @ViewChild('one') one:TemplateRef<any>;
    @ViewChild('two') two:TemplateRef<any>;
    

    and get the template references using

    <form no-validate (ngSubmit)="onSubmit(search)">
        <ng-container *ngFor="let part of objectKeys(config);">
            <ng-container *ngIf="config[part]">
                <ng-container [ngTemplateOutlet]="this[part]"></ng-container>
            </ng-container>
        </ng-container>
    </form>
    

    StackBlitz example

    0 讨论(0)
  • 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<any>;
      @ViewChild('two', { static: false }) two:TemplateRef<any>;
      @ViewChild('three', { static: false }) three:TemplateRef<any>;
    
      templateRefs: Array<TemplateRef<any>> = [];
    
      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

    <ng-container *ngFor="let template of templateRefs">
        <ng-container [ngTemplateOutlet]="template"></ng-container>
     </ng-container>
     
     <ng-template #one>
     <h1>Hello One</h1>
     </ng-template>
     
     <ng-template #two>
       <h1>Hello Two</h1>
     </ng-template>
     
     <ng-template #three>
       <h1>Hello Three</h1>
     </ng-template>
    
    
    0 讨论(0)
提交回复
热议问题