Waterfall vs Agile: Choosing the Right Software Development Methodology
Selecting the right software development methodology is one of the most important decisions for any project. The methodology you choose…
In Angular, the ‘#’ symbol inside a template is used to create a template reference variable. It’s a way to give a name to an element, component, or directive in your HTML, so that you can easily refer to it within that same template.
<input #myInput type="text">
<button (click)="alertValue(myInput.value)">Show Value</button>
Here:
Think of ‘#’ like putting a sticky note with a name on something on your page. If you label an input box ‘#myInput’, Angular will remember “that’s the input box,” so you can quickly point to it without searching for it in the DOM.
<input #usernameInp>
<p>You entered: {{ username.value }}</p>
<app-child #childComp></app-child>
<button (click)="childComp.doSomething()">Call Child Method</button>
<div #ngModuInp="ngModel" [(ngModel)]="name"></div>
<p>Valid: {{ ngModuInp.valid }}</p>
By default, template reference variables (declared with #) are accessible only within the template HTML. But sometimes, you want to interact with those elements, components, or templates directly in your TypeScript code. Angular provides the @ViewChild decorator for this.
Sample Code
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
<input #myInput type="text">
<button (click)="focusInput()">Focus Input</button>
`
})
export class MyComponent {
@ViewChild('myInput') myInputRef!: ElementRef<HTMLInputElement>;
focusInput() {
this.myInputRef.nativeElement.focus();
}
}
Here:
In Angular, ‘#’ is used to name something in your template so you can quickly refer to it like a shortcut to access an element, component, or directive without querying the DOM.
Using template reference variables with ‘#’ in Angular is a powerful and efficient way to interact with DOM elements, components, and directives directly from your templates or TypeScript code. By mastering this simple yet essential feature, you can write cleaner, more maintainable code without relying on complex DOM queries.
Partner with our experienced engineering team to turn your complex ideas into robust, high-performing applications.
Let's Talk About the Projects