這篇文章主要介紹了關於Angular如何正確的操作DOM,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
無奈接手了一個舊項目,上一個老哥在Angular專案中大量使用了JQuery來操作DOM,真的是太不講究了。那麼如何優雅的使用Angular的方式來操作DOM呢?
在組件的 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')); // 获取指定的子元素 }
## #@viewChild可以取得指定的元素, 指定的方式可以是本機變數或元件類型;
// HTML
3、@viewChildren -- You can use ViewChildren to get the {@link QueryList} of elements or directives from theview DOM.
指定selector的方式與@viewChild一致。
// 复制一个元素
@ViewChild(DialogComponent) viewcontent: DialogComponent; @ViewChildren(DialogComponent) viewcontents: QueryList; 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
引入
Renderer2 ,然後在construct中註入。 import { Component, OnInit , ViewContainerRef , ElementRef , ViewChild, , 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
,如下:
總結
以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!
相關推薦:
原生JS和jQuery分別使用jsonp來取得「目前天氣資訊」JavaScript Error對象的解析以上是Angular如何正確的操作DOM的詳細內容。更多資訊請關注PHP中文網其他相關文章!