angular操作Dom
1.通过原生JS操作
在ts文件中,在ngAfterViewInit()生命周期函数中(此时已经生成了DOM节点),通过原生js的方式可以获取该节点。
const div1: any = document.getElementById('box'); // any必须。否则报错
2、通过viewChild来获取节点
html:定义一个#xxxx
<div #getChild>
我是viewChild的数据
</div>
ts:引入viewChild,通过viewChild定义设置的#xxxx。此时对应的节点可以通过this.getChild.naticeElement来获取
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-dom',
templateUrl: './dom.component.html',
styleUrls: ['./dom.component.less']
})
export class DomComponent implements OnInit {
@ViewChild('getChild') getChild: any;
constructor() { }
public debug: any = true;
ngOnInit(): void {
}
ngAfterViewInit(): void { // 视图加载完成后触发的方法 dom加载完成
console.log(this.getChild.nativeElement.innerHTML);
}
}

浙公网安备 33010602011771号