搜尋
首頁web前端js教程Angular如何正確的操作DOM

Angular如何正確的操作DOM

Jul 07, 2018 am 10:30 AM
angular

這篇文章主要介紹了關於Angular如何正確的操作DOM,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

 無奈接手了一個舊項目,上一個老哥在Angular專案中大量使用了JQuery來操作DOM,真的是太不講究了。那麼如何優雅的使用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
<p class="tip-test-wrapper">
   
    <button class="test-get-dom"  (click)="getDomTest()">测试获取DOM</button>
 </p>
  <app-dialog></app-dialog>


// ts
import { DialogComponent } from &#39;./../../common/components/dialog/dialog.component&#39;;


@Component({
  selector: &#39;app-test-page&#39;,
  templateUrl: &#39;./test-page.component.html&#39;,
  styleUrls: [&#39;./test-page.component.scss&#39;]
})
export class TestPageComponent implements OnInit {
  // 通过本地变量获取元素  可通过read来指定获取的元素类型
  @ViewChild(&#39;testdom&#39; , { read: ViewContainerRef }) viewcontainer: ViewContainerRef;
  @ViewChild(&#39;testdom&#39;) viewelement: ElementRef;

  // 通过组件类型来获取
  @ViewChild(DialogComponent) viewcontent: DialogComponent;

  constructor(
    private el: ElementRef
  ) { }

  ngOnInit() {
  }

  getDomTest() {
    // console.dir(this.el.nativeElement.querySelector(&#39;.test-get-dom&#39;));
    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會傳回符合條件的第一個會傳回符合條件的第一view個元素,如果需要取得多個符合條件的元素呢?

@viewChildren會傳回所有符合條件的元素的list。

指定selector的方式與@viewChild一致。

// 复制一个元素
  <p class="tip-test-wrapper">
    <button class="test-get-dom" #testdom (click)="getDomTest()">测试获取DOM</button>
  </p>
  <p class="tip-test-wrapper">
    <button class="test-get-dom" #testdom (click)="getDomTest()">测试获取DOM</button>
  </p>
</p>
<app-dialog></app-dialog>
<app-dialog></app-dialog>// tsimport { DialogComponent } from &#39;./../../common/components/dialog/dialog.component&#39;;


@Component({
  selector: &#39;app-test-page&#39;,
  templateUrl: &#39;./test-page.component.html&#39;,
  styleUrls: [&#39;./test-page.component.scss&#39;]
})
export class TestPageComponent implements OnInit {

  @ViewChild(&#39;testdom&#39; , { read: ViewContainerRef }) viewcontainer: ViewContainerRef;
  @ViewChild(&#39;testdom&#39;) viewelement: ElementRef;  @ViewChildren(&#39;testdom&#39;) viewelements: QueryList<any>;
  @ViewChild(DialogComponent) viewcontent: DialogComponent;  @ViewChildren(DialogComponent) viewcontents: QueryList<DialogComponent>;

  constructor(    private el: ElementRef
  ) { }

  ngOnInit() {
  }

  getDomTest() {    // console.dir(this.el.nativeElement.querySelector(&#39;.test-get-dom&#39;));    // 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,  , ViewChildren, QueryList} from &#39;@angular/core&#39;;

import { DialogComponent } from &#39;./../../common/components/dialog/dialog.component&#39;;


@Component({
  selector: &#39;app-test-page&#39;,
  templateUrl: &#39;./test-page.component.html&#39;,
  styleUrls: [&#39;./test-page.component.scss&#39;]
})
export class TestPageComponent implements OnInit {

  @ViewChild(&#39;testdom&#39; , { read: ViewContainerRef }) viewcontainer: ViewContainerRef;
  @ViewChild(&#39;testdom&#39;) viewelement: ElementRef;
  @ViewChildren(&#39;testdom&#39;) viewelements: QueryList<any>;
  @ViewChild(DialogComponent) viewcontent: DialogComponent;
  @ViewChildren(DialogComponent) viewcontents: QueryList<DialogComponent>;

  constructor(
    private el: ElementRef
  ) { }

  ngOnInit() {
  }

  getDomTest() {

    
  }
}
  

renderer2提供了豐富的API供使用

,如下:

總結

#  透過elementRef或@ viewChild @viewChildren取得元素,再透過renderer2提供的API來操作元素。不過記得在不要在 ngAfterViewInit 週期之前使用。透過Angular提供的方式,可以滿足大部分的操作DOM的需求了。如果有特殊的場景,當然還是原生DOM擼起來呀

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

原生JS和jQuery分別使用jsonp來取得「目前天氣資訊」


JavaScript Error對象的解析

以上是Angular如何正確的操作DOM的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript是用C編寫的嗎?檢查證據JavaScript是用C編寫的嗎?檢查證據Apr 25, 2025 am 12:15 AM

是的,JavaScript的引擎核心是用C語言編寫的。 1)C語言提供了高效性能和底層控制,適合JavaScript引擎的開發。 2)以V8引擎為例,其核心用C 編寫,結合了C的效率和麵向對象特性。 3)JavaScript引擎的工作原理包括解析、編譯和執行,C語言在這些過程中發揮關鍵作用。

JavaScript的角色:使網絡交互和動態JavaScript的角色:使網絡交互和動態Apr 24, 2025 am 12:12 AM

JavaScript是現代網站的核心,因為它增強了網頁的交互性和動態性。 1)它允許在不刷新頁面的情況下改變內容,2)通過DOMAPI操作網頁,3)支持複雜的交互效果如動畫和拖放,4)優化性能和最佳實踐提高用戶體驗。

C和JavaScript:連接解釋C和JavaScript:連接解釋Apr 23, 2025 am 12:07 AM

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

從網站到應用程序:JavaScript的不同應用從網站到應用程序:JavaScript的不同應用Apr 22, 2025 am 12:02 AM

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python vs. JavaScript:比較用例和應用程序Python vs. JavaScript:比較用例和應用程序Apr 21, 2025 am 12:01 AM

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C/C在JavaScript口譯員和編譯器中的作用C/C在JavaScript口譯員和編譯器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在行動中:現實世界中的示例和項目JavaScript在行動中:現實世界中的示例和項目Apr 19, 2025 am 12:13 AM

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)