To further explain, I want to populate an ng-container based on a list of ng-templates. Each ng-template is added one after the other. In other words ng-template contains two buttons previous and next. previous removes current ng-template and returns the previous template. Next button removes the current ng-template and adds the next ng-template.
My issue is referencing each template using TemplateRef in component.ts. I tried getting each template reference from the component.ts constructor but this doesn't work. My code below explains the approach I used.
home.component.html
<div >
<!-- Ng Container -->
<ng-container *ngTemplateOutlet="activeTemplate">
</ng-container>
<!-- Select Service -->
<ng-template #allServices>
<!-- TODO -->
</ng-template>
<!-- Select Worker -->
<ng-template #worker>
<!-- TODO -->
</ng-template>
<!-- Display Calendar -->
<ng-template #calendar>
<!-- TODO -->
</ng-template>
<!-- User entails user details -->
<ng-template #userDetails>
<!-- TODO -->
</ng-template>
</div>
home.component.ts
import { Component, VERSION, TemplateRef, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular ' VERSION.full;
templates: TemplateRef<any>[] = [];
activeTemplate: TemplateRef<any>;
constructor(private templateRef: TemplateRef<any>) {
this.templates = [
this.templateRef.allServices, // Error occurs
this.templateRef.worker, // Error occurs
this.templateRef.calendar, // Error occurs
this.templateRef.userDetails // Error occurs
];
this.activeTemplate = this.templates[0];
}
}
You can see how I am trying to pull out each reference but this does not work. I should also say I am very new to Angular and I read the documentation for TemplateRef
from angular and to my understanding ElementRef
is supposed to be the reference of the template.
CodePudding user response:
When you inject in constructor templateRef this is about your component home.component. You need get the templates using ViewChild
ViewChild('allServices',{static:true}) template0:TemplateRef<any>
ViewChild('worker',{static:true}) template1:TemplateRef<any>
ViewChild('calendar',{static:true}) template2:TemplateRef<any>
ViewChild('userDetails',{static:true}) template3:TemplateRef<any>
And use
index=0;
this.activeTemplate = this['template' index];
butyou asign the variable activeTemplate in ngOnInit
(or in ngAfterViewInit if you don't use {static:true}
) not in constructor
see stackblitz