在Angular中有两种方式来获取DOM元素:ViewChild和document.querySelector。ViewChild是Angular的一个装饰器,它允许你在新版本中通过@ViewChild和@ViewChildren引用组件中的DOM元素,而不用使用原生方式来查询DOM。而document.querySelector方法是原生的js方法,它可以返回与指定的选择器或选择器中的一个或多个元素匹配的第一个元素。
下面是两种获取DOM元素的示例代码:
@ViewChild('myElement') myElement: ElementRef;
ngAfterViewInit(): void { console.log(this.myElement.nativeElement); }
//在HTML模板中
const element = document.querySelector('#myElement'); console.log(element);
//在HTML模板中
以上两种方法都可以获取DOM元素。使用ViewChild方法能够更好地与Angular的工作方式相匹配,而使用document.querySelector方法在一些特定的情况下也是有用的,如在没有访问Component的上下文的情况下获取DOM元素。