您好,欢迎访问一九零五行业门户网

一文聊聊Angular中怎么操作DOM元素

angular中怎么操作dom元素?下面本篇文章给大家介绍一下angular操作dom元素的方法,希望对大家有所帮助!
在angular获取dom元素可以使用javascript的原生api,或者引入jquery通过jquery对象操作dom,但angular已经给我们提供了相应的api(elementref)来获取dom元素,就没必要使用原生的api或者jquery了。【相关教程推荐:《angular教程》】
elementref 获取dom元素1、创建testcomponent组件,模板如下:test.component.html
<div> <p>你好</p></div><div> <span>世界</span></div><h1>标题</h1><pass-badge id="component" textcolor="red">组件</pass-badge>
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组件,为对应元素加上模板变量,如下
<div> <p>你好</p></div><!-- 1、给元素加入模板变量 div --><div #div> <span>世界</span></div><h1>标题</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、引入viewchildimport { 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元素的详细内容。
其它类似信息

推荐信息