// ElementRef
// <span #spanRef>I am span</span>
@ViewChild("spanRef") spanRef: ElementRef;
ngAfterViewInit(): void {
// outputs `I am span`
console.log(this.spanRef.nativeElement.textContent);
}
// This is the most basic abstraction. If you observe it’s class structure, you’ll see that it only holds
// the native element it’s associated with. It’s useful for accessing native DOM element.
// However, such usage is discouraged by Angular team. Not only it poses security risk, but it also creates
// tight coupling between your application and rendering layers which makes is difficult to run an app
// on multiple platforms
// ElementRef can be returned for any DOM element using ViewChild decorator.
// TemplateRef
/* <ng-template #tpl>
<span>I am span in template</span>
</ng-template>
*/
@ViewChild("tpl") tpl: TemplateRef<any>;
// ViewContainerRef
// Represents a container where one or more views can be attached.
// The first thing to mention here is that any DOM element can be used as a view container.
// What’s interesting is that Angular doesn’t insert views inside the element, but appends them after
// the element bound to ViewContainer. This is similar to how router-outlet inserts components.
/*
<span>I am first span</span>
<ng-container #vc></ng-container>
<span>I am last span</span>
<ng-template #tpl>
<span>I am span in template</span>
</ng-template>
*/
@ViewChild("vc", {read: ViewContainerRef}) vc: ViewContainerRef;
@ViewChild("tpl") tpl: TemplateRef<any>;
ngAfterViewInit() {
let view = this.tpl.createEmbeddedView(null);
this.vc.insert(view);
}
// ViewContainer also provides API to create a view automatically:
this.vc.createEmbeddedView(this.tpl)
// ngTemplateOutlet is further a shortcut
/*
<span>I am first span</span>
<ng-container [ngTemplateOutlet]="tpl"></ng-container>
<span>I am last span</span>
<ng-template #tpl>
<span>I am span in template</span>
</ng-template>
*/