Angular

    Custom Angular TemplateRef with Dynamic Content


    Introduction

    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.

    Why Use TemplateRef?

    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.

    Example: Creating a Custom TemplateRef Directive

    The directive will accept TemplateRef instances which it will dynamically display.

    Create the Directive (custom-template.directive.ts)

    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);}}

    Use the Directive in a Component

    <ng-template #dynamicTemplate let-name="name"><p>Hello, {{ name }}!</p></ng-template><div *appCustomTemplate="{ name: 'Angular' }" [appCustomTemplate]="dynamicTemplate"></div>

    How It Works

    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.

    Conclusion

    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

    Comment

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    Angular

    Related Center Of Excellence