詳解如何在angular2中獲取節(jié)點(diǎn)
我們知道在angular2中ts文件支持js代碼,為什么用document.getElementById沒法獲取元素節(jié)點(diǎn)呢?
其實(shí)在angular2中先加載ts文件,再加載view,所以獲取不到節(jié)點(diǎn)。
在應(yīng)用層直接操作 DOM,就會(huì)造成應(yīng)用層與渲染層之間強(qiáng)耦合,導(dǎo)致我們的應(yīng)用無法運(yùn)行在不同環(huán)境,如 web worker 中,因?yàn)樵?web worker 環(huán)境中,是不能直接操作 DOM。
通過 ElementRef 我們就可以封裝不同平臺(tái)下視圖層中的 native 元素 (在瀏覽器環(huán)境中,native 元素通常是指 DOM 元素),最后借助于 Angular 提供的強(qiáng)大的依賴注入特性,我們就可以輕松地訪問到 native 元素。
angular2有生命周期鉤子AfterViewInit可以幫助我們?cè)趘iew加載完之后再執(zhí)行相應(yīng)的ts
ts:
import { Component, ElementRef ,AfterViewInit} from '@angular/core';
exportclassAppComponent {
constructor(privateelementRef: ElementRef) {
}
ngAfterViewInit() {
let divEle =this.elementRef.nativeElement.querySelector('div');//獲取第一個(gè)div
console.dir(divEle);
let div = doxcument.getElementById("div"); //獲取id為‘div'的節(jié)點(diǎn)
}
}
下面有一種優(yōu)化方案,運(yùn)用angular內(nèi)置屬性裝飾器@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的標(biāo)識(shí)"#name",@ViewChild根據(jù)這個(gè)搜索元素
angular中怎么獲取dom元素
步驟分解:
第一步:給要獲取的元素一個(gè)ng-model變量,并且綁定事件啦!
<div class="home" ng-model="dirName" ng-mouseenter="switchImage($event,dirName)"></div> //給要獲取的元素一個(gè)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”分別對(duì)應(yīng)著“上,右,下,左”
// 將點(diǎn)的坐標(biāo)對(duì)應(yīng)的弧度值換算成角度度數(shù)值
var dirName = new Array('上方','右側(cè)','下方','左側(cè)');
if(e.type == 'mouseenter' && direction == 1){
$(this).find('.profil-photo').html(dirName[direction]+'離開');
}else{
$(this).find('.profil-photo').html(dirName[direction]+'離開');
}
});
}
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
如何使用AngularJs打造權(quán)限管理系統(tǒng)【簡易型】
這篇文章主要介紹了使用AngularJs打造權(quán)限管理系統(tǒng)【簡易型】的相關(guān)資料,需要的朋友可以參考下2016-05-05
對(duì)angularJs中controller控制器scope父子集作用域的實(shí)例講解
今天小編就為大家分享一篇對(duì)angularJs中controller控制器scope父子集作用域的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-10-10
angular.foreach 循環(huán)方法使用指南
本文主要介紹了angular.foreach 循環(huán)方法使用格式及參數(shù),是篇非常基礎(chǔ)的文章,與需要的小伙伴參考下2015-01-01
AngularJS中的API(接口)簡單實(shí)現(xiàn)
本文主要介紹AngularJS API(接口),這里對(duì)AngularJS API的知識(shí)做了詳細(xì)講解,并附簡單代碼實(shí)例,有需要的小伙伴可以參考下2016-07-07

