Angular provides TemplateRef as a feature to create dynamic templates which users can use repeatedly. TemplateRef serves as a useful approach for developing UI elements which switch between varied content according to present context.
Enables dynamic rendering of templates.
Provides flexibility in component content.
Using templates helps reduce repetition of written code since they can be reused multiple times.
The directive will accept TemplateRef instances which it will dynamically display.
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appCustomTemplate]'
})
export class CustomTemplateDirective {
constructor(
private viewContainer: ViewContainerRef,
private templateRef: TemplateRef<any>
) {}
@Input() set appCustomTemplate(context: any) {
this.viewContainer.clear();
this.viewContainer.createEmbeddedView(this.templateRef, context);
}
}
<ng-template #dynamicTemplate let-name="name">
<p>Hello, {{ name }}!</p>
</ng-template>
<div *appCustomTemplate="{ name: 'Angular' }" [appCustomTemplate]="dynamicTemplate"></div>
The template (ng-template) defines a dynamic variable (name).
The template moves to the appCustomTemplate directive through passing.
The directive processes and displays the template inside the target area utilizing the supplied context data.
Components stay reusable alongside maintaining cleanliness through the implementation of TemplateRef. TemplateRef works optimally for generating dynamic interfaces and creating modals or reusable interface elements.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.
Contact Us