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 #username>
<p>Entered: {{ username.value }}</p>
<app-child #childComp></app-child>
<button (click)="childComp.doSomething()">Call Child Method</button>
<div #ngModelRef="ngModel" [(ngModel)]="name"></div>
<p>Valid: {{ ngModelRef.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.
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:
<input ref-myInput>
This is less common but works the same.
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.
Work with our skilled Angular developers to accelerate your project and boost its performance.
Hire Angular Developers