How to select an element in a component template with Angular?

Sometimes, we want to select an element in a component template with Angular.

In this article, we’ll look at how to select an element in a component template with Angular.

How to select an element in a component template with Angular?

To select an element in a component template with Angular, we can assign an ref to the element in the template.

Then we can use ViewChild to access it.

For instance, we write

import { Component, ElementRef, ViewChild } from "@angular/core";

@Component({
  selector: "my-app",
  template: ` <input #inputEl value="hello" /> `,
  styleUrls: ["./app.component.css"],
})
export class AppComponent {
  @ViewChild("inputEl") inputEl: ElementRef;

  ngAfterViewInit() {
    console.log(this.inputEl);
  }
}

to assign the inputEl ref to the input element.

Then we access the element with

@ViewChild("inputEl") inputEl: ElementRef

in the template.

We call ViewChild with the ref name.

Then we use this.inputEl to get the element in our component method.

Conclusion

To select an element in a component template with Angular, we can assign an ref to the element in the template.