angular获取dom元素的两种方式

1,568 阅读1分钟

之前一直使用原生方法获取dom元素,比如

document.getElementById('元素的id');
document.querySelector('#id名');
document.querySelector('.类名');

但是在框架里面还是尽量避免直接操作dom,angular提供了获取dom元素的方式。

方式一:viewChild

<div #box></div>
@ViewChild('box') box: ElementRef;
​
constructor(){
    
}
ngOnInit(){
    console.log(this.box.nativeElement);
}

方式二:ElementRef

<div class="box"></div>
constructor(private el: ElementRef){
    
}
ngOnInit(){
    console.log(this.el.nativeElement.querySelector('.box'));
}

感谢原作者:SevenLonely,出处:简书在该作者文章中查找