In Angular, a template reference variable is a variable that allows you to get a reference to a DOM element or directive in your component's template. You can use this variable to manipulate the element or directive programmatically.
To create a template reference variable, you need to add the '#' symbol followed by a name to the element or directive in your template. Here's an example:
<input #myInput type="text">
<button (click)="logInputValue(myInput.value)">Log Input Value</button>
In this example, we're creating a template reference variable called 'myInput' for the input element. We're also binding to the click event of a button and passing the value of the input element to a function called 'logInputValue'.
In our component class, we can define the 'logInputValue' function like this:
logInputValue(value: string) {
console.log(value);
}
When we click the button, the 'logInputValue' function will be called with the value of the input element.
Template reference variables can also be used with directives. Here's an example:
<div #myDiv appHighlight>Highlighted Div</div>
In this example, we're creating a template reference variable called 'myDiv' for a div element and applying the 'appHighlight' directive to it. The 'appHighlight' directive could be defined like this:
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
The 'HighlightDirective' sets the background color of the element it's applied to to yellow. In our component class, we could use the 'myDiv' template reference variable to get a reference to the highlighted div and manipulate it programmatically.
Comments
Post a Comment