【资料图】
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是什么
所以就可以通过this.el.nativeElement.querySelector("#component")来操作对应的DOM元素。例如改变文字颜色就可以
this.el.nativeElement.querySelector("#component").style.color = "lightblue"登录后复制模板变量获取DOM元素
1、修改TestComponent组件,为对应元素加上模板变量,如下
你好
世界标题
组件
登录后复制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"// 文字颜色修改为淡蓝色 }}登录后复制最终结果如下
更多编程相关知识,请访问:编程教学!!
以上就是详解angular中操作DOM元素的方法的详细内容,更多请关注php中文网其它相关文章!


























































