在构造函数中注入ElementRef并使用ViewChild获取DOM元素的引用。
例如,如果要获取一个id为“myElement”的div元素的引用,代码应该如下所示:
在组件类中,导入ViewChild和ElementRef,如下所示:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({ selector: 'my-component', template: '
' }) export class MyComponent { @ViewChild('myElement', { static: false }) myElementRef: ElementRef;constructor(private elementRef: ElementRef) {}
ngAfterViewInit() { console.log(this.myElementRef.nativeElement); // outputs the DOM element } }
在这个例子中,ViewChild用于获取指向myElement的引用,并且ElementRef用于在构造函数中注入组件的整个DOM元素。最终,您可以使用myElementRef.nativeElement来访问DOM元素。