今天完成的事情:学习angular中操作dom
明天计划的事情:学习angular 的使用
遇到的问题:
收获:
Angular中获取DOM节点操作
ngOnInit() {
//组件和指令初始化完成 并不是真正的dom加载完成
let oBox:any=document.getElementById('box');
console.log(oBox.innerHTML);
oBox.style.color="red";
//获取不到dom节点
/*
let oBox1:any=document.getElementById('box1');
console.log(oBox1.innerHTML);
oBox1.style.color="blue";
*/
}
//视图加载完成以后触发的方法 dom加载完成 (一般把dom操作放在这个里面)
ngAfterViewInit(){
let oBox1:any=document.getElementById('box1');
console.log(oBox1.innerHTML);
oBox1.style.color="blue";
}
上面是原生js获取dom节点的操作。
import { Component, OnInit,ViewChild} from '@angular/core';
export class NewsComponent implements OnInit {
//获取dom节点
@ViewChild('myBox') myBox:any;
//获取一个子组件
@ViewChild('header') header:any;
constructor() { }
ngOnInit() {
}
ngAfterViewInit(): void {
console.log(this.myBox.nativeElement);
this.myBox.nativeElement.style.width='100px';
this.myBox.nativeElement.style.height='100px';
this.myBox.nativeElement.style.background='red';
console.log(this.myBox.nativeElement.innerHTML);
}
getChildRun(){
//调用子组件里面的方法
this.header.run();
}
}
ViewChild获取dom节点
1、模板中给dom起一个名字
<div #myBox>
我是一个dom节点
</div>
2、在业务逻辑里面引入ViewChild
import { Component, OnInit,ViewChild} from '@angular/core';
3、 写在类里面 @ViewChild('myBox') myBox:any;
4、ngAfterViewInit生命周期函数里面获取dom
this.myBox.nativeElement
ViewChild对原生js封装了同时父组件也可以通过ViewChild调用子组件
评论