javascript / beginner
Snippet
Accessing Elements with @ViewChild
The @ViewChild decorator allows you to access a child component or a DOM element directly from within your component class using a template reference variable.
snippet.js
1
2
3
4
5
6
7
8
@Component({ selector: 'app-root', template: '<input #myInput>' })export class AppComponent {@ViewChild('myInput') inputElement!: ElementRef;focusInput() {this.inputElement.nativeElement.focus();}}
angular
Breakdown
1
@ViewChild('myInput')
Queries the template for the reference named 'myInput'.
2
inputElement!: ElementRef;
Declares a variable to store the reference to the DOM element.
3
this.inputElement.nativeElement
Accesses the actual underlying HTML element in the browser.