DOM操作
ngAfterViewInit(){
//原生JS操作
var boxDom:any=document.getElementById('box');
boxDom.style.color='red';
}
//@ViewCHild操作DOM
import { Component ,ViewChild,ElementRef} from '@angular/core';
@ViewChild('myattr') myattr: ElementRef;
<div #myattr></div>
let attrEl = this.myattr.nativeElement;
父子組件中通過 ViewChild 調(diào)用子組件 的方法
//調(diào)用子組件給子組件定義一個(gè)名稱
<app-footer #footerChild></app-footer>
// 引入 ViewChild
import { Component, OnInit ,ViewChild} from '@angular/core';
// ViewChild 和剛才的子組件關(guān)聯(lián)起來
@ViewChild('footerChild') footer;
//調(diào)用子組件
run(){this.footer.footerRun(); }
//html
<app-header #header></app-header>
<div #myBox>
我是一個(gè)dom節(jié)點(diǎn)
</div>
<button (click)="getChildRun()">獲取子組件的方法</button>
//js代碼
/*
ViewChild獲取dom節(jié)點(diǎn)
1、模板中給dom起一個(gè)名字
<div #myBox>
我是一個(gè)dom節(jié)點(diǎn)
</div>
2、在業(yè)務(wù)邏輯里面引入ViewChild
import { Component, OnInit,ViewChild} from '@angular/core';
3、 寫在類里面 @ViewChild('myBox') myBox:any;
4、ngAfterViewInit生命周期函數(shù)里面獲取dom
this.myBox.nativeElement
*/
import { Component, OnInit,ViewChild} from '@angular/core';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {
//獲取dom節(jié)點(diǎn)
@ViewChild('myBox') myBox:any;
//獲取一個(gè)組件
@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(){
//調(diào)用子組件里面的方法
this.header.run()
}
}
CSS動(dòng)畫
ngOnInit() {
//組件和指令初始化完成 并不是真正的dom加載完成
let oBox:any=document.getElementById('box');
console.log(oBox.innerHTML);
oBox.style.color="red";
//獲取不到dom節(jié)點(diǎn)
/*
let oBox1:any=document.getElementById('box1');
console.log(oBox1.innerHTML);
oBox1.style.color="blue";
*/
}
//視圖加載完成以后觸發(fā)的方法 dom加載完成 (建議把dom操作放在這個(gè)里面)
ngAfterViewInit(){
let oBox1:any=document.getElementById('box1');
console.log(oBox1.innerHTML);
oBox1.style.color="blue";
}
hideAside(){
//原生js獲取dom節(jié)點(diǎn)
var asideDom:any=document.getElementById('aside');
asideDom.style.transform="translate(100%,0)";
}