新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

angular中怎么操作DOM元素

本篇内容主要讲解“angular中怎么操作DOM元素”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“angular中怎么操作DOM元素”吧!

成都创新互联主要从事成都网站建设、做网站、网页设计、企业做网站、公司建网站等业务。立足成都服务北票,10多年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575

在angular获取DOM元素可以使用javascript的原生API,或者引入jQuery通过jquery对象操作DOM,但angular已经给我们提供了相应的API(ElementRef)来获取DOM元素,就没必要使用原生的API或者jQuery了。

ElementRef 获取DOM元素

1、创建TestComponent组件,模板如下:test.component.html

你好

    世界

标题

组件

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是什么

angular中怎么操作DOM元素
所以就可以通过this.el.nativeElement.querySelector('#component')来操作对应的DOM元素。例如改变文字颜色就可以

this.el.nativeElement.querySelector('#component').style.color = 'lightblue'

模板变量获取DOM元素

可以通过ViewChild获取组件,同样的还有ContentChildViewChildrenContentChildren

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'	// 文字颜色修改为淡蓝色
    }
}

最终结果如下

angular中怎么操作DOM元素

由结果我们可以知道,当使用ViewChild模板变量获取组件元素时,获取到的是组件导出的组件类(上例是PassBadgeComponent),这时候只可以操作组件中含有的属性。

当使用ViewChild模板变量获取html元素时,获取到的时ElementRef类型的类,这时可以通过this.div.nativeElement.querySelector('span')等原生API来操作元素

到此,相信大家对“angular中怎么操作DOM元素”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!


新闻标题:angular中怎么操作DOM元素
分享路径:http://www.wjwzjz.com/article/ihpeii.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP