How to access DOM elements in Angular?
In Angular, you can use the ViewChild decorator to access DOM elements.
Firstly, import ViewChild and ElementRef in the class of the component.
import { ViewChild, ElementRef } from '@angular/core';
Next, declare a ViewChild property in the component class and annotate it with the ElementRef type.
@ViewChild('myElement', {static: false}) myElement: ElementRef;
In the template, define a reference variable using the # symbol and pass it to the ViewChild property.
<div #myElement>这是一个 DOM 元素</div>
Next, in the component class, the myElement property can be used to access the DOM element. The actual object of the DOM element can be obtained through the nativeElement property.
ngAfterViewInit() {
console.log(this.myElement.nativeElement);
}
Note: ViewChild retrieves a reference to a DOM element, so it is important to ensure that the DOM element has been rendered before accessing it. The ngAfterViewInit lifecycle hook can be used to guarantee that the DOM element has been rendered.
In addition, you can also access DOM elements using directives, such as @ViewChild(MyDirective), where MyDirective is a custom directive.