Skip to content
Advertisement

Angular – How do directives “see” template & ViewContainer?

I have a simple component which injects numbers after a delay via custom directive named *appDelay

I already know that * is a hint for Angular to de-sugar the syntax into something like

JavaScript

I also know that we can Inject components/templates to the viewContainer via :

JavaScript

The directive code is :

JavaScript

The docs states :

To access a ViewContainerRef of an Element, you can either place a Directive injected with ViewContainerRef on the Element, or you obtain it via a ViewChild query.

Question:

In a general pseudo form : What are the template “string values” for templateRef and viewContainerRef ?

IMHO the de-sugared template would be something like:

JavaScript

So the ViewContainerRef would be a reference to <ng-template ...>

And the templateRef will be a reference to the <card >...</card>

— Is that correct ?

(Also , is it possible to console.log() those HTML templates and see the actual markup ?

https://plnkr.co/edit/80AGn8bR4CiyH0ceP8ws?p=preview

Advertisement

Answer

ViewContainerRef just point to element that will be host for inserting views. Those views will be added as siblings to this host element.

For structural directive comment like <!----> will be host element.

Desugar for

JavaScript

will be

JavaScript

it also can be described like so:

JavaScript

Since ng-template is not stamped to the DOM it will be rendered as <!---->.

Angular will create ViewContainerRef with reference to this comment tag.

JavaScript

Each ViewContainer can have only one anchor element and each anchor element can only have a single ViewContainer. ViewContainer is a container that helps you to manipulate Views(ViewRef, EmbeddedViewRef)

Also TemplateRef instance will be created

JavaScript

and its elementRef(anchor or location) will point to the same comment element.

The main feature of TemplateRef is having template property

JavaScript

This property doesn’t contains html string but describes view

JavaScript

will print

JavaScript

so this is our template. As you can see it describes view with div root element and child text node with text n Hoorayn

Angular uses such ViewDefinitions which are located in ngfactories to build the DOM treeenter image description here

See also

Don’t forget to watch https://www.youtube.com/watch?v=EMjTp12VbQ8

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement