1
votes

In the custom structure directive example at following link, what does TemplateRef and ViewContainerRef point to?

https://angular.io/guide/structural-directives#unless

A Directive usually doesn't have a view. So would templateRef point to the HTML tag or Component the directive is attached to? Eg In the following code, the template is everything between <p> ...</p>? I read that * gets converted to <ng-template> so it could be the case.

<p *myUnless="condition">Show this sentence unless the condition is true.</p>

What is ViewContainerRef in the example? Generally I would add a <ng-container> as view container? Where does it come from in the example?

1

1 Answers

1
votes

This example

<p *myUnless="condition">Show this sentence unless the condition is true.</p>

is transformed by the compiler into

<ng-template [myUnless]="condition">
   <p>Show this sentence unless the condition is true.</p>
<ng-template>

So you can see now that myUnless directive is placed on the ng-template element and that's why it has access to the templateRef

So would templateRef point to the HTML tag or Component the directive is attached to?

It "sort of" points to the contents of the ng-template element the directive is attached to. Under the hood it references the embedded view definition created for the ng-template contents.

What is ViewContainerRef in the example?

Any HTML element can act as a view container. So again, in this case the directive injects the view container that references directive host element.

The ng-template element is rendered as comment DOM node, so you will see that both ViewContaineRef and TemplateRef point to this comment node:

export class MyUnless {
  constructor(t: TemplateRef<any>, vc: ViewContainerRef) {
    console.log(t.elementRef.nativeElement.nodeName); // #comment
    console.log(t.elementRef.nativeElement === vc.element.nativeElement); // true
  }
}