詳解Angular如何正確的操作DOM
無奈接手了一個舊項目,上一個老哥在Angular項目中大量使用了JQuery來操作DOM,真的是太不講究了。那么如何優(yōu)雅的使用Angular的方式來操作DOM呢?
獲取元素
1、ElementRef --- A wrapper around a native element inside of a View.
在組件的 constructor中注入ElementRef,可以獲取到整個組件元素的包裹。
@Component({
selector: 'app-test-page',
templateUrl: './test-page.component.html',
styleUrls: ['./test-page.component.scss']
})
export class TestPageComponent implements OnInit {
constructor(
private el: ElementRef
) { }
ngOnInit() {
}
getDomTest() {
console.dir(this.el);
}
}

ElementRef中的nativeElement即是組件最外層的DOM元素。再通過原生的DOM定位方式,即可獲取到指定的selector元素。
getDomTest() {
console.dir(this.el.nativeElement.querySelector('.test-get-dom')); // 獲取指定的子元素
}
2、@viewChild() --- You can use ViewChild to get the first element or the directive matching the selector from the view DOM.
@viewChild可以獲取指定的元素, 指定的方式可以是本地變量或者組件類型;
// HTML
<div class="tip-test-wrapper">
// 本地變量綁定button按鈕
<button class="test-get-dom" #testdom (click)="getDomTest()">測試獲取DOM</button>
</div>
// Dialog組件
<app-dialog></app-dialog>
// ts
import { DialogComponent } from './../../common/components/dialog/dialog.component';
@Component({
selector: 'app-test-page',
templateUrl: './test-page.component.html',
styleUrls: ['./test-page.component.scss']
})
export class TestPageComponent implements OnInit {
// 通過本地變量獲取元素 可通過read來指定獲取的元素類型
@ViewChild('testdom' , { read: ViewContainerRef }) viewcontainer: ViewContainerRef;
@ViewChild('testdom') viewelement: ElementRef;
// 通過組件類型來獲取
@ViewChild(DialogComponent) viewcontent: DialogComponent;
constructor(
private el: ElementRef
) { }
ngOnInit() {
}
getDomTest() {
// console.dir(this.el.nativeElement.querySelector('.test-get-dom'));
console.dir(this.viewcontainer);
console.dir(this.viewelement);
console.dir(this.viewcontent);
}
}

備注:ElementRef或者 @viewChild 獲取元素,一定要在 ngAfterViewInit 周期之后再使用。
3、@viewChildren -- You can use ViewChildren to get the {@link QueryList} of elements or directives from theview DOM.
@viewChild會返回符合條件的第一個元素,如果需要獲取多個符合條件的元素呢? @viewChildren會返回所有符合條件的元素的list。 指定selector的方式與@viewChild一致。
// 復制一個元素
<div class="tip-test-wrapper">
<button class="test-get-dom" #testdom (click)="getDomTest()">測試獲取DOM</button>
</div>
<div class="tip-test-wrapper">
<button class="test-get-dom" #testdom (click)="getDomTest()">測試獲取DOM</button>
</div>
</div>
<app-dialog></app-dialog>
<app-dialog></app-dialog>
// ts
import { DialogComponent } from './../../common/components/dialog/dialog.component';
@Component({
selector: 'app-test-page',
templateUrl: './test-page.component.html',
styleUrls: ['./test-page.component.scss']
})
export class TestPageComponent implements OnInit {
@ViewChild('testdom' , { read: ViewContainerRef }) viewcontainer: ViewContainerRef;
@ViewChild('testdom') viewelement: ElementRef;
@ViewChildren('testdom') viewelements: QueryList<any>;
@ViewChild(DialogComponent) viewcontent: DialogComponent;
@ViewChildren(DialogComponent) viewcontents: QueryList<DialogComponent>;
constructor(
private el: ElementRef
) { }
ngOnInit() {
}
getDomTest() {
// console.dir(this.el.nativeElement.querySelector('.test-get-dom'));
// console.dir(this.viewcontainer);
console.dir(this.viewelement);
console.dir(this.viewelements);
console.dir(this.viewcontent);
console.dir(this.viewcontents);
}

操作DOM --- Renderer2
在獲取dom之后,如何對dom進行操作呢?原生的domAPI是一種選擇,但是Angular提供了更好的跨平臺方式 Renderer2。
引入 Renderer2 , 然后在construct中注入。
import { Component, OnInit , ViewContainerRef , ElementRef , ViewChild, Renderer2 , ViewChildren, QueryList} from '@angular/core';
import { DialogComponent } from './../../common/components/dialog/dialog.component';
@Component({
selector: 'app-test-page',
templateUrl: './test-page.component.html',
styleUrls: ['./test-page.component.scss']
})
export class TestPageComponent implements OnInit {
@ViewChild('testdom' , { read: ViewContainerRef }) viewcontainer: ViewContainerRef;
@ViewChild('testdom') viewelement: ElementRef;
@ViewChildren('testdom') viewelements: QueryList<any>;
@ViewChild(DialogComponent) viewcontent: DialogComponent;
@ViewChildren(DialogComponent) viewcontents: QueryList<DialogComponent>;
constructor(
private render: Renderer2,
private el: ElementRef
) { }
ngOnInit() {
}
getDomTest() {
// 修改元素顏色
this.render.setStyle(this.viewelement.nativeElement , 'color' , 'red');
}
}
renderer2提供了豐富的API供使用,如下:

總結(jié)
通過elementRef或者@viewChild @viewChildren獲取元素,再通過renderer2提供的API來操作元素。不過記得在不要在 ngAfterViewInit 周期之前使用。通過Angular提供的方式,可以滿足大部分的操作DOM的需求了。如果有特殊的場景,當然還是原生DOM擼起來呀
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
利用Angularjs中模塊ui-route管理狀態(tài)的方法
這篇文章主要給大家介紹了如何用Angularjs中的模板ui-route來管理狀態(tài)的方法,文中通過示例代碼介紹的很詳細,相信對大家的理解和學習具有一定的參考借鑒價值,有需要的朋友可以一起來學習學習。2016-12-12
angularJs在多個控制器中共享服務(wù)數(shù)據(jù)的方法
今天小編就為大家分享一篇angularJs在多個控制器中共享服務(wù)數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
AngularJs定制樣式插入到ueditor中的問題小結(jié)
這篇文章主要介紹了AngularJs定制樣式插入到ueditor中的問題小結(jié)的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-08-08
分享使用AngularJS創(chuàng)建應用的5個框架
如果你計劃使用AngularJS創(chuàng)建你的Web應用,那現(xiàn)在就開始吧。你不需要有任何的恐懼和擔心,因為現(xiàn)在有很多的框架都可以很好地支持AngularJS2015-12-12
Angular應用tsconfig.json中的lib屬性示例解析
這篇文章主要介紹了Angular應用tsconfig.json中的lib屬性示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07

