How can I select an element in a component template?
Answers (1)
Add AnswerTo select element follow the step:
- Add template reference variable in component.html file
- Import @ViewChild decorator.
- Use @ViewChild decorator to use template reference variable in the component.
- select the element in ngAfterViewInit method.
In app-test.component.html file add input element with reference variable.
<input #inputElement value=”CodeHubs”>
Now write code in app-test.component.ts file
import { Component, OnInit, ViewChild, ElementRef } from ‘@angular/core’;
@Component({
selector: ‘app-test’,
templateUrl: ‘./app-test.component.html’,
styleUrls: [‘./app-test.component.scss’]
})
export class TestComponent implements OnInit {
@ViewChild(‘inputElement’) inputElement:ElementRef;
constructor() { }
ngOnInit() {
}
ngAfterViewInit() {
console.log(this.inputElement.nativeElement.value);
}
}
It will display value of input element as CodeHubs in console.