Angular中怎么操作DOM元素?下面本篇文章給大家介紹一下angular操作DOM元素的方法,希望對(duì)大家有所幫助!
在angular獲取DOM元素可以使用
javascript的原生API
,或者引入jQuery通過jquery對(duì)象
操作DOM,但angular已經(jīng)給我們提供了相應(yīng)的API(ElementRef
)來獲取DOM元素,就沒必要使用原生的API或者jQuery了?!鞠嚓P(guān)教程推薦:《angular教程》】
ElementRef 獲取DOM元素
1、創(chuàng)建TestComponent
組件,模板如下:test.component.html
<div> <p>你好</p> </div> <div> <span>世界</span> </div> <h1>標(biāo)題</h1> <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')
來操作對(duì)應(yīng)的DOM元素。例如改變文字顏色就可以
this.el.nativeElement.querySelector('#component').style.color = 'lightblue'
模板變量獲取DOM元素
可以通過
ViewChild
獲取組件,同樣的還有ContentChild
,ViewChildren
和ContentChildren
1、修改TestComponent
組件,為對(duì)應(yīng)元素加上模板變量,如下
<div> <p>你好</p> </div> <!-- 1、給元素加入模板變量 div --> <div #div> <span>世界</span> </div> <h1>標(biāo)題</h1> <!-- 給組件加入模板變量 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
模板變量獲取組件元素時(shí),獲取到的是組件導(dǎo)出的組件類(上例是PassBadgeComponent
),這時(shí)候只可以操作組件中含有的屬性。當(dāng)使用
ViewChild
模板變量獲取html元素時(shí),獲取到的時(shí)ElementRef
類型的類,這時(shí)可以通過this.div.nativeElement.querySelector('span')
等原生API來操作元素