Reputation: 3037
I am reading a tutorial and I have found a sample code with a line looking like this:
<input #foo />
I think that it's an input with id="foo". But isn't the correct syntax this one:
<input id="foo" />
Upvotes: 0
Views: 697
Reputation: 5962
It's called a template reference variable in Angular. it can refer to a DOM element,Directive or web component etc. According to the official documentation -
A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component.
Source : https://angular.io/guide/template-syntax#ref-vars
Example : We can use @ViewChild()
with Template Variable using ElementRef
to access Native Element. @ViewChild()
can instantiate ElementRef
corresponding to a given template reference variable. The template variable name will be passed in @ViewChild()
as an argument.
HTML :
<div>
Name: <input type="text" #name> <br/>
City: <input type="text" #city>
</div>
Component code :
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-theme',
templateUrl: './apptheme.component.html'
})
export class AppThemeComponent implements AfterViewInit {
@ViewChild('name')
private elName : ElementRef;
@ViewChild('city')
private elCity : ElementRef;
ngAfterViewInit() {
this.elName.nativeElement.style.backgroundColor = 'cyan';
this.elName.nativeElement.style.color = 'red';
this.elCity.nativeElement.style.backgroundColor = 'cyan';
this.elCity.nativeElement.style.color = 'red';
}
}
using #name and #city
above we can access the native elements style properties.
Upvotes: 1