Structural directives in Angular like *ngIf and *ngFor aren’t just handy—they’re powerful tools for dynamic DOM manipulation. But what if you need custom logic that controls what shows up in the UI? That’s where ViewContainerRef and TemplateRef come in. Together, they let you build advanced structural directives that render content conditionally based on complex logic like user permissions, roles, or feature flags.
What Do ViewContainerRef and TemplateRef Actually Do?
- TemplateRef is like a blueprint for the DOM. It represents the content inside an ng-template and allows you to reuse that content wherever needed.
- ViewContainerRef is the placeholder where you inject or remove views. It controls when and how the template gets added to the DOM.
These two are often used together in structural directives to decide whether certain parts of the UI should be created or destroyed based on logic you define.
Real Example: A Custom *appHasPermission Directive
This directive only renders its content if a user has a specific permission.
import { Directive, Input, TemplateRef, ViewContainerRef, OnDestroy } from '@angular/core';
import { AuthService } from './auth.service';
import { Subscription } from 'rxjs';
@Directive({ selector: '[appHasPermission]'
})
export class HasPermissionDirective implements OnDestroy { private subscription: Subscription; private hasView = false; constructor( private templateRef: TemplateRef<unknown>, private viewContainer: ViewContainerRef, private authService: AuthService ) {} @Input() set appHasPermission(permission: string) { this.subscription = this.authService.hasPermission(permission).subscribe(canView => { if (canView && !this.hasView) { this.viewContainer.createEmbeddedView(this.templateRef); this.hasView = true; } else if (!canView && this.hasView) { this.viewContainer.clear(); this.hasView = false; } }); } ngOnDestroy() { this.subscription?.unsubscribe(); }
}
Usage in a template: <div *appHasPermission="'edit-article'">...</div>
Final Thoughts
When used right, structural directives can make your app leaner, faster, and easier to manage. ViewContainerRef and TemplateRef aren’t just for framework authors, they’re powerful tools every serious Angular dev should understand. If you’re aiming to build advanced features without reinventing the wheel, it’s a smart move to hire Angular developers who already know how to apply these patterns efficiently.