美文网首页
angular获取dom元素

angular获取dom元素

作者: SevenLonely | 来源:发表于2019-05-07 13:59 被阅读0次

方式一: ViewChild

<div #box></div>
@ViewChild('box') box: ElementRef;

constructor(){
 // 不能放在构造函数里面这个时候构造函数中还没有视图没法获取到box元素
}

ngOnInit() {
    console.log(this.box.nativeElement);
}

方式二: ElementRef

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

相关文章

网友评论

      本文标题:angular获取dom元素

      本文链接:https://www.haomeiwen.com/subject/tpheoqtx.html