您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“angular中怎么操作DOM元素”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“angular中怎么操作DOM元素”吧!
在angular獲取DOM元素可以使用
javascript的原生API
,或者引入jQuery通過jquery對象
操作DOM,但angular已經(jīng)給我們提供了相應(yīng)的API(ElementRef
)來獲取DOM元素,就沒必要使用原生的API或者jQuery了。
1、創(chuàng)建TestComponent
組件,模板如下:test.component.html
<div>
<p>你好</p>
</div>
<div>
<span>世界</span>
</div>
<h2>標(biāo)題</h2>
<pass-badge id="component" textColor="red">組件</pass-badge>
2、編寫test.component.ts
文件
import { Component, OnInit } from '@angular/core';
// 1、導(dǎo)入 ElementRef 類
import { ElementRef} from '@angular/core';
import { PassBadge } from './compoment/pass-badge/pass-badge.component'
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css'],
declarations: [ PassBadge ]
})
export class TestComponent implements OnInit {
// 2、將 ElementRef 類注入 test 組件中
constructor(private el:ElementRef) {}
ngOnInit() {
// 3、獲取 DOM 元素
console.log(this.el.nativeElement)
console.log(this.el.nativeElement.querySelector('#component'))
}
}
我們來看看this.el.nativeElement
是什么
所以就可以通過this.el.nativeElement.querySelector('#component')
來操作對應(yīng)的DOM元素。例如改變文字顏色就可以
this.el.nativeElement.querySelector('#component').style.color = 'lightblue'
可以通過
ViewChild
獲取組件,同樣的還有ContentChild
,ViewChildren
和ContentChildren
1、修改TestComponent
組件,為對應(yīng)元素加上模板變量,如下
<div>
<p>你好</p>
</div>
<!-- 1、給元素加入模板變量 div -->
<div #div>
<span>世界</span>
</div>
<h2>標(biāo)題</h2>
<!-- 給組件加入模板變量 component -->
<pass-badge #component textColor="red">組件</pass-badge>
2、修改test.component.ts
,如下:
import { Component, OnInit } from '@angular/core';
import { ElementRef} from '@angular/core';
// 2、引入ViewChild
import { ViewChild } from '@angular/core'
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
constructor(private el:ElementRef) {}
// 3、獲取元素
@ViewChild('component') dom: any;
@ViewChild('div') div: any;
ngOnInit() {
console.log(this.dom) // PassBadgeComponent
this.dom.fn() // 調(diào)用 passbadge 組件的 fn 方法
console.log(this.div) // ElementRef
this.div.nativeElement.style.color = 'lightblue' // 文字顏色修改為淡藍(lán)色
}
}
最終結(jié)果如下
由結(jié)果我們可以知道,當(dāng)使用
ViewChild
模板變量獲取組件元素時,獲取到的是組件導(dǎo)出的組件類(上例是PassBadgeComponent
),這時候只可以操作組件中含有的屬性。當(dāng)使用
ViewChild
模板變量獲取html元素時,獲取到的時ElementRef
類型的類,這時可以通過this.div.nativeElement.querySelector('span')
等原生API來操作元素
到此,相信大家對“angular中怎么操作DOM元素”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。