Reputation: 1297
Hey I am learning now angular 2 step by step and I have build a Structural Custom Directive which called unless. Unless act the same as ngIf act, if my condition is true attach the element to the dom otherwise detach it. Here is the template where I operate the directive:
<h1>Structural Custom Directive</h1>
<h2>*unless</h2>
<div id="container">
<div *unless="switch" id="conditional-text">Conditional Text</div>
</div>
<button (click)="onSwitch()">Switch</button>
I have a field in my main component which called switch and for every clicking of a button I traverse the value of switch like this:
onSwitch(){
this.switch = !this.switch;
}
Now the code of the directive is like this:
import { Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';
@Directive({
selector: '[unless]'
})
export class UnlessDirective {
@Input() set unless(condition: Boolean){
if (condition){
this.vcRef.createEmbeddedView(this.templateRef);
}else{
this.vcRef.clear();
}
console.log('this.vcRef', this.vcRef);
console.log('this.templateRef', this.templateRef);
}
constructor(private templateRef: TemplateRef<any>,private vcRef: ViewContainerRef) { }
}
For condition=true I adding the templateref to my embeddedView otherwise I clear the viewContainerRef. Now my question is basic,what is the viewContainerRef, does it point to the div with container id? or maybe this is the document object. I can't figure out to where the viewContainerRef is refering to.
I know that every structrual directive like ngIf is desugar into the following:
<template [ngIf]=”condition”>
<p>My Content</p>
</template>
Therefore I know the templateRef is refer to the template element above,but I can't understand to where viewContainerRef is point to?
I have tried to print the viewContainerRef and all I got is a comment which I don't know from where does it come from.
Upvotes: 1
Views: 2558
Reputation: 14087
Think of ViewContainerRef
as an anchor point in the DOM where you can insert/remove templates and components programmatically.
In your case the location of that anchor point is indeed the point where <div *unless>
is situated. But don't think of it as a DOM node or a piece of markup. It's an Angular concept so it doesn't really have an equivalent.
Really it's just a container whose content you can control programmatically.
https://angular.io/docs/ts/latest/api/core/index/ViewContainerRef-class.html
Upvotes: 3