I\'m using ngTemplateOutlet with dynamic value.
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
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>