An embedded view can be referenced from a component other than the hosting component whose template defines it, or it can be defined independently by a TemplateRef. What is the meaning of the above statement?
I couldn't understand the difference between templateRef and embeddedViewRef
CodePudding user response:
TemplateRef is a basically reference to a template - a RULE for piece of html that you don't see yet, but you can build many pieces of html with it.
EmbeddedViewRef is a reference to already rendered piece of html. It could have been built with the help of some Template ref. The reason it is called "embedded" is because it is bound to its parent component change detection and in most cases also to its injector tree
<ng-template #myTpl> <!-- here is a template, and myTpl is a template ref.
no html will be rendered in this place at all,
it is like a function, that has not been called yet
-->
<div> some content </div>
</ng-template>
<div *ngTemplateOutlet="myTpl">
<!-- here we use myTpl template to create embedded view with
the help of ngTempalteOutlet directive.
This directive will have embeddedViewRef in its code and this is the place where we will have some html rendered
-->
</div>
CodePudding user response:
In Angular, the ViewContainerRef class represents a container where one or more views can be attached. The ViewContainerRef is created as a result of ViewChild or ContentChild decorator, or it can be obtained using the ViewContainerRef injector.
The EmbeddedViewRef is a type of ViewRef that represents an embedded view. An embedded view is a view that has been created from a TemplateRef and that has been attached to a ViewContainerRef.
The TemplateRef is a reference to an Angular template. It is a lightweight context object that is created for each embedded view, and that exposes the template element, the current context variables, and a way to create an EmbeddedViewRef from the template.
To summarize, the ViewContainerRef is a container for views, the EmbeddedViewRef is a view that has been attached to a container, and the TemplateRef is a reference to an Angular template that can be used to create an EmbeddedViewRef and attach it to a container.
Hope it's solve your doubt.
Thanks!