Angular 4 TemplateRef vs ViewContainerRef

Asked on July 19, 2017
What is difference between Angular 4 TemplateRef and ViewContainerRef? When should we use TemplateRef and when should we use ViewContainerRef?

Replied on April 26, 2018
TemplateRef
It represents an embedded template that can be used to instantiate embedded views.
<ng-template #msg>
Welcome to you.<br/>
Happy learning!
</ng-template>
export class CpMsgComponent implements AfterViewInit {
@ViewChild('msg')
private msgTempRef : TemplateRef<any>
----
}
ViewContainerRef
It represents a container where one or more views can be attached. We can use its methods such as createEmbeddedView() and createComponent()
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
@Directive({
selector: '[cpIf]'
})
export class CpIfDirective {
constructor( private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) { }
@Input() set cpIf(condition: boolean) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}

Replied on April 26, 2018
Find the example using <ng-template> with TemplateRef and ViewContainerRef
message.directive.ts
import { Directive, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[cpMsg]' }) export class MessageDirective { constructor(public viewContainerRef: ViewContainerRef) { } }
cp-msg.component.ts
import { Component, ViewChild, ViewChildren, AfterViewInit,
TemplateRef, ViewContainerRef, QueryList } from '@angular/core'; import { MessageDirective } from './message.directive'; @Component({ selector: 'app-msg', templateUrl: './cp-msg.component.html' }) export class CpMsgComponent implements AfterViewInit { @ViewChild('msg') private msgTempRef : TemplateRef<any> @ViewChildren(MessageDirective) private queryList: QueryList<MessageDirective> ngAfterViewInit() { this.queryList.map(messageDirective => messageDirective.viewContainerRef.createEmbeddedView(this.msgTempRef)); } }
cp-msg.component.html
<ng-template #msg> Welcome to you.<br/> Happy learning! </ng-template> <h3>Message </h3> <div cpMsg> </div> <h3>Message </h3> <div cpMsg> </div>
Find the link https://www.concretepage.com/angular-2/angular-4-ng-template-example#TemplateRef