angular中dom操作
ngOnInit()方法
ngOnInit()方法是组件和指令初始化完成,并不是真正的dom加载完成。
示例html模板:
<div id="box1">
this is text1
</div>
<div id="box2" *ngIf="flag">
this is text2
</div>
示例typescript程序:
ngOnInit(): void {
// box1不涉及到angular组件模板合成,可以正常获取操作
let box1:any = document.getElementById('box1');
console.log(box1.innerHTML);
box1.style.color = 'red';
// box2中含有ngIf语句,在执行ngOnInit时box2节点未渲染,box2此处获取不到
let box2:any = document.getElementById('box2');
console.log(box2.innerHTML);
box2.style.color = 'yellow';
}
ngAfterViewInit()方法
视图加载完毕后执行
实例typescript程序:
// 真正的dom加载完成
ngAfterViewInit(): void {
//Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
//Add 'implements AfterViewInit' to the class.
let box1:any = document.getElementById('box1');
console.log(box1.innerHTML);
box1.style.color = 'red';
let box2:any = document.getElementById('box2');
console.log(box2.innerHTML);
box2.style.color = 'yellow';
}
ViewChild
在ts中,可以使用原生js的document.getElementById获取标签,也可以使用ViewChild获取标签和子组件
- 在组件的html模板中定义div、子组件,并配置
#名称
```html
2.
在组件的ts文件中获取div和子组件,并调用子组件的方法
```typescript
// 加入ViewChild
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {
// 获取myBox
@ViewChild('myBox') myBox:any;
// 获取myHeader
@ViewChild('myHeader') myHeader:any;
ngAfterViewInit(): void {
// 通过this.myBox.nativeElement获取dom节点
console.log(this.myBox.nativeElement.innerHTML);
this.myBox.nativeElement.style.color = 'red';
// 调用myHeader子组件的run方法
this.myHeader.run();
}
}
- 也可以在父组件中使用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(); } } ```