Angular: Understanding TemplateRef and ViewContainerRef in Custom Directives

Abhishek Wadalkar
2 min readSep 8, 2024

--

When creating custom structural directives in Angular, two important references are used: TemplateRef and ViewContainerRef. In this post, we will delve into the details of these references and how they are used in custom structural directives.

TemplateRef

TemplateRef represents an embedded template in an Angular component. It is a reference to the <ng-template> element in the component's template. When Angular encounters a structural directive, it converts the host element into an embedded template using the <ng-template> tags.

ViewContainerRef

ViewContainerRef represents the container where the embedded template will be rendered. It is a reference to the view container where the host element is defined. The view container is the context where the embedded template will be added or removed.

How They Work Together

When a custom structural directive is applied to an element, Angular creates an embedded template from the host element using TemplateRef. The directive can then use ViewContainerRef to add or remove the embedded template from the view container.

Example

Let’s revisit the ifFalse directive example:

TypeScript

@Directive({
selector: '[IfFalse]'
})
export class IfFalseDirective {
private templateRef = inject(TemplateRef);
private viewContainer = inject(ViewContainerRef);
private embeddedTemplateAdded = false;

@Input() set IfFalse(condition: boolean) {
if (!condition && !this.embeddedTemplateAdded) {
this.viewContainer.createEmbeddedView(this.templateRef);
this.embeddedTemplateAdded = true;
} else if (condition && this.embeddedTemplateAdded) {
this.viewContainer.clear();
this.embeddedTemplateAdded = false;
}
}
}

In this example:

  • TemplateRef is injected to reference the embedded template created by Angular.
  • ViewContainerRef is injected to reference the view container where the host element is defined.
  • The @Input() setter receives a condition to evaluate.
  • If the condition is false and the embedded template has not been added, createEmbeddedView() is called to add the template to the view container.
  • If the condition is true and the embedded template has been added, clear() is called to remove the template from the view container.

Conclusion

In this post, we explored the roles of TemplateRef and ViewContainerRef in custom structural directives. By understanding how these references work together, you can create powerful custom directives that manipulate the DOM based on dynamic conditions.

--

--

Abhishek Wadalkar
Abhishek Wadalkar

Written by Abhishek Wadalkar

Passionate Frontend developer with 4 years experience, crafting seamless, user-centric web experiences. Exploring the world of web development and constantly.

No responses yet