Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access TemplateRef on the component of Angular?

Component TS

ngOnInit() {
    if(somecondition)
        // This is the line of code that wont work
        this.openModal(#tempName);
}

Component HTML

<ng-template #tempName>
    I got some content here
</ng-template>

this.openModal(#tempName) -> How do i get access to the ngTemplate tempName here?

like image 328
Flyn Sequeira Avatar asked Aug 31 '18 05:08

Flyn Sequeira


People also ask

How do I access ng-template in component?

To access the above ng-template in the component or directive, first, we need to assign a template reference variable. #sayHelloTemplate is that variable in the code below. Now, we can use the ViewChild query to inject the sayHelloTemplate into our component as an instance of the class TemplateRef .

What is TemplateRef in Angular?

TemplateReflinkRepresents an embedded template that can be used to instantiate embedded views. To instantiate embedded views based on a template, use the ViewContainerRef method createEmbeddedView() .


1 Answers

Flyn you put in your code

@ViewChild('tempName') mymodal: ElementRef;
//You can NOT use this.mymodal at ngInit, the early time you can use is in ngAfterViewInit
ngAfterViewInit()
{
 if (somecondition)
   this.openModal(mymodal);
}
like image 59
Eliseo Avatar answered Oct 23 '22 17:10

Eliseo