angular中dom操作

ngOnInit()方法

ngOnInit()方法是组件和指令初始化完成,并不是真正的dom加载完成。

示例html模板:

  1. <div id="box1">
  2. this is text1
  3. </div>
  4. <div id="box2" *ngIf="flag">
  5. this is text2
  6. </div>

示例typescript程序:

  1. ngOnInit(): void {
  2. // box1不涉及到angular组件模板合成,可以正常获取操作
  3. let box1:any = document.getElementById('box1');
  4. console.log(box1.innerHTML);
  5. box1.style.color = 'red';
  6. // box2中含有ngIf语句,在执行ngOnInit时box2节点未渲染,box2此处获取不到
  7. let box2:any = document.getElementById('box2');
  8. console.log(box2.innerHTML);
  9. box2.style.color = 'yellow';
  10. }

ngAfterViewInit()方法

视图加载完毕后执行

实例typescript程序:

  1. // 真正的dom加载完成
  2. ngAfterViewInit(): void {
  3. //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
  4. //Add 'implements AfterViewInit' to the class.
  5. let box1:any = document.getElementById('box1');
  6. console.log(box1.innerHTML);
  7. box1.style.color = 'red';
  8. let box2:any = document.getElementById('box2');
  9. console.log(box2.innerHTML);
  10. box2.style.color = 'yellow';
  11. }

ViewChild

在ts中,可以使用原生js的document.getElementById获取标签,也可以使用ViewChild获取标签和子组件

  1. 在组件的html模板中定义div、子组件,并配置 #名称 ```html

test myBox节点

  1. 2.
  2. 在组件的ts文件中获取div和子组件,并调用子组件的方法
  3. ```typescript
  4. // 加入ViewChild
  5. import { Component, OnInit, ViewChild } from '@angular/core';
  6. @Component({
  7. selector: 'app-news',
  8. templateUrl: './news.component.html',
  9. styleUrls: ['./news.component.less']
  10. })
  11. export class NewsComponent implements OnInit {
  12. // 获取myBox
  13. @ViewChild('myBox') myBox:any;
  14. // 获取myHeader
  15. @ViewChild('myHeader') myHeader:any;
  16. ngAfterViewInit(): void {
  17. // 通过this.myBox.nativeElement获取dom节点
  18. console.log(this.myBox.nativeElement.innerHTML);
  19. this.myBox.nativeElement.style.color = 'red';
  20. // 调用myHeader子组件的run方法
  21. this.myHeader.run();
  22. }
  23. }
  1. 也可以在父组件中使用ViewChild获取子组件对象 ```typescript import { AfterViewInit, ViewChild } from ‘@angular/core’; import { Component } from ‘@angular/core’; import { CountdownTimerComponent } from ‘./countdown-timer.component’;

@Component({ selector: ‘app-countdown-parent-vc’, template: <h3>Countdown to Liftoff (via ViewChild)</h3> <button (click)="start()">Start</button> <button (click)="stop()">Stop</button> <div class="seconds">{{ seconds() }}</div> <app-countdown-timer></app-countdown-timer>, styleUrls: [‘../assets/demo.css’] }) export class CountdownViewChildParentComponent implements AfterViewInit {

@ViewChild(CountdownTimerComponent) private timerComponent: CountdownTimerComponent;

seconds() { return 0; }

ngAfterViewInit() { setTimeout(() => this.seconds = () => this.timerComponent.seconds, 0); }

start() { this.timerComponent.start(); } stop() { this.timerComponent.stop(); } } ```