
在angular获取dom元素可以使用
javascript的原生api,或者引入jquery通过jquery对象操作dom,但angular已经给我们提供了相应的api(elementref)来获取dom元素,就没必要使用原生的api或者jquery了。【相关教程推荐:《angular教程》】
elementref 获取dom元素
1、创建testcomponent组件,模板如下:test.component.html
你好
世界详解angular中操作dom元素的方法-尊龙凯时
组件
2、编写test.component.ts文件
import { component, oninit } from '@angular/core';
// 1、导入 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')来操作对应的dom元素。例如改变文字颜色就可以
this.el.nativeelement.queryselector('#component').style.color = 'lightblue'模板变量获取dom元素
可以通过
viewchild获取组件,同样的还有contentchild,viewchildren和contentchildren
1、修改testcomponent组件,为对应元素加上模板变量,如下
你好
世界组件
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() // 调用 passbadge 组件的 fn 方法
console.log(this.div) // elementref
this.div.nativeelement.style.color = 'lightblue' // 文字颜色修改为淡蓝色
}
}最终结果如下

由结果我们可以知道,当使用
viewchild模板变量获取组件元素时,获取到的是组件导出的组件类(上例是passbadgecomponent),这时候只可以操作组件中含有的属性。当使用
viewchild模板变量获取html元素时,获取到的时elementref类型的类,这时可以通过this.div.nativeelement.queryselector('span')等原生api来操作元素
更多编程相关知识,请访问:编程教学!!
以上就是详解angular中操作dom元素的方法的详细内容,更多请关注其它相关文章!
王杉65883988