1 原生js的dom获取相同
.html文件<div id="app"> zheshi</div><div id="app1" *ngIf="expression"> dom加载完成</div>.ts文件 ngOnInit() { let Dom:any = document.getElementById('app') console.log(Dom.innerHTML); Dom.style.color = "red" } ngAfterViewInit(): void { //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only. //Add 'implements AfterViewInit' to the class. let obox:any = document.getElementById('app1') console.log(obox.innerHTML); obox.style.color = 'yellow' }
2 通过angular自带的ViewChild去获取dom
.html文件
<div #box>
dom节点
</div>
.ts文件
import { Component, OnInit,ViewChild } from '@angular/core';
//引入组件ViewChild
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {
@ViewChild('box') Box:any;
// @ViewChild('在html文件中以#开头的名字') 赋值给Box:any;
constructor() { }
ngOnInit() {
}
ngAfterViewInit(): void {
//Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
//Add 'implements AfterViewInit' to the class.
console.log(this.Box.nativeElement);
this.Box.nativeElement.style.color = 'red'