我們知道在angular2中ts文件支持js代碼,為什么用document.getElementById沒法獲取元素節點呢?
其實在angular2中先加載ts文件,再加載view,所以獲取不到節點。
在應用層直接操作 DOM,就會造成應用層與渲染層之間強耦合,導致我們的應用無法運行在不同環境,如 web worker 中,因為在 web worker 環境中,是不能直接操作 DOM。
通過 ElementRef 我們就可以封裝不同平臺下視圖層中的 native 元素 (在瀏覽器環境中,native 元素通常是指 DOM 元素),最后借助于 Angular 提供的強大的依賴注入特性,我們就可以輕松地訪問到 native 元素。
angular2有生命周期鉤子AfterViewInit可以幫助我們在view加載完之后再執行相應的ts
ts:
import { Component, ElementRef ,AfterViewInit} from '@angular/core'; exportclassAppComponent { constructor(privateelementRef: ElementRef) { } ngAfterViewInit() { let divEle =this.elementRef.nativeElement.querySelector('div');//獲取第一個div console.dir(divEle); let div = doxcument.getElementById("div"); //獲取id為‘div'的節點 } }
下面有一種優化方案,運用angular內置屬性裝飾器@ViewChild
ts:
import{ Component, ElementRef, ViewChild, AfterViewInit }from'@angular/core'; exportclassAppComponent{ @ViewChild('greet') greetDiv: ElementRef; ngAfterViewInit() {this.greetDiv.nativeElement.style.backgroundColor ='red'; } }
html:
<div #greet>hello world</div> //element的標識"#name",@ViewChild根據這個搜索元素
angular中怎么獲取dom元素
步驟分解:
第一步:給要獲取的元素一個ng-model變量,并且綁定事件啦!
第二步:在controller中利用$event.target獲取dom元素即可!
$scope.switchImage = function($event, value) { 3 $($event.target).on("mouseenter mouseleave",function(e) { var w = $(this).width(); // 得到盒子寬度 var h = $(this).height();// 得到盒子高度 var x = (e.pageX - this.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1); // 獲取x值 var y = (e.pageY - this.offsetTop - (h / 2)) * (h > w ? (w / h) : 1); // 獲取y值 var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; //direction的值為“0,1,2,3”分別對應著“上,右,下,左” // 將點的坐標對應的弧度值換算成角度度數值 var dirName = new Array('上方','右側','下方','左側'); if(e.type == 'mouseenter' && direction == 1){ $(this).find('.profil-photo').html(dirName[direction]+'離開'); }else{ $(this).find('.profil-photo').html(dirName[direction]+'離開'); } }); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。