1 原生js的dom获取相同

  1. .html文件
  2. <div id="app">
  3. zheshi
  4. </div>
  5. <div id="app1" *ngIf="expression">
  6. dom加载完成
  7. </div>
  8. .ts文件
  9. ngOnInit() {
  10. let Dom:any = document.getElementById('app')
  11. console.log(Dom.innerHTML);
  12. Dom.style.color = "red"
  13. }
  14. ngAfterViewInit(): void {
  15. //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
  16. //Add 'implements AfterViewInit' to the class.
  17. let obox:any = document.getElementById('app1')
  18. console.log(obox.innerHTML);
  19. obox.style.color = 'yellow'
  20. }

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'