Angular ViewRef, ViewContainerRef, TemplateRef and ElementRef are very important to understand. We always use them at least indirectly.


A ViewRef can be an <ng-template /> (TemplateRef) or component template (hostView).

this.embeddedViewRef = this.templateRef.createEmbeddedView({ $implicit: 'Angular', dateNow: new Date() });

It is also interesting to mention that a ViewRef extends ChangeDetectorRef, which means that change detection is a key part of every ViewRef.

For example we can create a component and append it outside of the RootComponent (AppComponent) and still attach it to the change detection cycles.

const modalRef = createComponent(ModalComponent, { environmentInjector: this.injector });

// This includes the component into change detection cycles. (ApplicationRef)


A ViewContainer represents a collection of ViewRef items. We can obtain a ViewContainerRef for every element in the template through dependency injection in a component, a directive or a @ViewChild({ read: ViewContainerRef }) decorated property in a component / directive.

ViewContainerRef will NOT hold children inside itself. It will insert a ViewRef AFTER itself as a sibling.
(The router-outlet works like that as well).


A TemplateRef represents an <ng-template />.

<ng-template let-name let-date="dateNow">{{date}} - Hello {{name}}!</ng-template>

An <ng-template /> itself will not do anything at all.
We need a ViewContainerRef to insert the template somewhere.

this.embeddedViewRef = this.viewContainerRef.createEmbeddedView(this.templateRef, { $implicit: 'Angular', dateNow: new Date() });

Which is a shorthand for:

this.embeddedViewRef = this.templateRef.createEmbeddedView({ $implicit: 'Angular', dateNow: new Date() });

The template will then be rendered as following.

Hello Angular!

To remove the template:


Indirectly we do the same thing with an ngIf directive all the time. ngIf internally does exactly that.


An ElementRef is a wrapper around a DOM element (nativeElement). = 'yellow';

// Or better by using the Renderer2:
this.renderer.setStyle(this.elementRef.nativeElement, 'backgroundColor', 'yellow');

Why we should use Renderer2?

Renderer2 encapsulates the DOM access which allows us to intercept it's behavior or even render something other than DOM. This can be useful for different platforms like SSR / Server-Side Rendering.