Angular Template Refs - An Introduction

    As an Angular developer, you must be familiar with data binding and templates. Templates are a significant part of the Angular framework and are used to create reusable components. In this article, we will learn about Angular template refs, an essential element of the Angular framework.

    Template refs are a way to get a reference to a template element in your view. They allow us to interact with specific elements in a template and apply custom logic when manipulating the view.

    What Are Angular Templates?

    Templates are a central part of building Angular applications. In Angular, templates are used to generate the view of a component. They allow us to mix HTML elements with Angular directives that control the rendering of those elements.

    The simplest way to define an Angular template is to use the inline template syntax. Here's an example:

    <app-component>
        <h1>{{ title }}</h1>
        <p>{{ message }}</p>
    </app-component>
    

    In the code snippet above, we can see that the component template consists of a title and a message. The data is defined as properties on the component class and bound to the template using curly braces ({{}}).

    Angular provides us with a variety of different directive types that we can use in a template. Directives such as ngFor, ngIf, and ngSwitch allow us to conditionally render content or loop over a data set. Using these directives, we can create complex views that react dynamically to changes in the underlying data.

    What Are Template Refs?

    Template refs provide a way to interact with a specific element in a template. They allow us to reference the element directly in our component class, which opens up many different possibilities for customizing the behavior of the view.

    Template refs are created by adding a hash symbol (#) to the HTML element, followed by a name for the reference. Here's an example:

    <input #myInput />
    

    In this example, we define a template ref named "myInput" on an input element. This reference can be accessed from the component class by adding an @ViewChild decorator and specifying the name of the template ref:

    @ViewChild('myInput') myInput: ElementRef;
    

    With this code, we can now access the input element directly from the component class using the "myInput" property. This property can be used to access the value of the input, set focus on the input, or manipulate it in any other way.

    Using Template Refs in Angular Components

    Template refs are especially useful when building reusable components. They allow us to expose specific elements in the template to the parent component, which can then customize them as needed.

    Let's take an example of a simple component that displays a list of items. In its template, we define a template ref for the list element:

    <ul #itemList>
        <li *ngFor="let item of items">{{ item }}</li>
    </ul>
    

    In the component class, we can access the template ref using the @ViewChild decorator and then pass it to the parent component using an @Output decorator:

    export class ItemListComponent {
      @ViewChild('itemList') itemList: ElementRef;
      @Output() onItemSelected = new EventEmitter();
    
      selectItem(item: any) {
        // highlight the selected item
        this.itemList.nativeElement.children
          .forEach((child: any) => child.classList.remove('selected'));
        event.target.classList.add('selected');
    
        // emit the selected item to the parent component
        this.onItemSelected.emit(item);
      }
    }
    

    In this code, we define an onItemSelected event that can be raised when the user clicks on an item in the list. When an item is selected, we highlight it by adding a "selected" class to its HTML element using template refs. We then emit the selected item to the parent component using the onItemSelected event.

    Conclusion

    Template refs are a powerful tool for building Angular applications. They allow us to interact with specific elements in a template directly from the component class, providing us with a high degree of flexibility in customizing the behavior of our views.

    By using template refs in our components, we can build more reusable and customizable components that perform specific tasks, such as manipulating the DOM or managing user input.

    If you're new to Angular, it's recommended that you learn more about templates and data binding, as these are essential concepts that form the foundation of the Angular framework.

    © 2023 Designed & Developed by José Matos.