发布于 2026-01-06 7 阅读
0

ElementRef in Angular | How to use it

Angular 中的 ElementRef | 如何使用它

Angular 的 ElementRef 是对原生 DOM 元素(HTML 元素)对象的封装。它包含一个名为 nativeElement 的属性,该属性保存着对底层 DOM 对象的引用。我们可以使用它来操作 DOM。在组件类中,我们使用 ViewChild 来获取 HTML 元素的 ElementRef。此外,当你在构造函数中请求时,Angular 还会注入组件或指令的 Host 元素的 ElementRef。在本教程中,我们将探讨如何使用 ElementRef 来获取 HtmlElement 的引用并在 Angular 应用程序中操作 DOM。

*目录:*

  1. 元素引用
  2. 在组件类中获取 ElementRef
  3. 元素引用示例
  4. 自定义指令中的 ElementRef
  5. ElementRef 和 XSS 注入攻击
  6. 参考资料

元素引用

DOM 对象由浏览器创建和维护,它们代表文档的结构和内容。在原生 JavaScript 代码中,我们通过访问这些 DOM 对象来操作视图。我们可以创建和构建文档,浏览其结构,以及添加、修改或删除元素和内容。

Angular 提供了许多用于操作 DOM 的工具和技巧。我们可以添加/删除组件。它还提供了许多指令,例如类指令和样式指令,用于操作组件的样式等等。

在某些情况下,我们可能仍然需要访问 DOM 元素。这时 ElementRef 就派上用场了。

在组件类中获取 ElementRef

要使用 ElementRef 操作 DOM,我们需要在组件/指令中获取对 DOM 元素的引用。

嵌入:获取组件中对 DOM 元素的引用

  1. 为组件/指令中的元素创建模板引用变量。
  2. 使用模板变量,通过 ViewChild 或 ViewChildren 将元素注入到组件类中。

获取承载组件/指令的 DOM 元素

  1. 在构造函数中请求 ElementRef(Angular 依赖注入),Angular 会注入承载组件/指令的引用元素。例如,在以下代码中,变量 hello 指的是 HTML 元素 div。
<div #hello>Hello Angular</div>
Enter fullscreen mode Exit fullscreen mode

hello 是模板引用变量,我们可以在模板中使用它。

在组件类中,我们使用 ViewChild 注入 hello 元素。Angular 将 hello 元素以 ElementRef 类型注入。

@ViewChild('hello', { static: false }) divHello: ElementRef;
Enter fullscreen mode Exit fullscreen mode

读取令牌

请看以下示例

<input #nameInput [(ngModel)]="name">
Enter fullscreen mode Exit fullscreen mode

nameInput 模板引用变量现在绑定到输入元素。但与此同时,我们还对其应用了 ngModel 指令。

在这种情况下,我们可以使用读取令牌来告知 Angular 我们需要 ElementRef 引用,如下所示。

//ViewChild returns ElementRef i.e. input HTML Element

@ViewChild('nameInput',{static:false, read: ElementRef}) elRef;


//ViewChild returns NgModel associated with the nameInput
@ViewChild('nameInput',{static:false, read: NgModel}) inRef;

Enter fullscreen mode Exit fullscreen mode

元素引用示例

一旦我们有了 ElementRef,我们就可以使用 nativeElement 属性来操作 DOM,如下所示。

import { Component,ElementRef, ViewChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-root',
  template:  '<div #hello>Hello</div>'
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

 @ViewChild('hello', { static: false }) divHello: ElementRef;

 ngAfterViewInit() {
   this.divHello.nativeElement.innerHTML = "Hello Angular";
 }

}
Enter fullscreen mode Exit fullscreen mode

你可以非常轻松地操作 DOM。

  ngAfterViewInit() {
    this.divHello.nativeElement.innerHTML = "Hello Angular";
    this.divHello.nativeElement.className="someClass";
    this.divHello.nativeElement.style.backgroundColor="red";
  }
Enter fullscreen mode Exit fullscreen mode

自定义指令中的 ElementRef

ElementRef 的一个应用场景是 Angular 指令。我们学习了如何在 Angular 中创建自定义指令。以下是 ttClass 自定义属性指令的代码。

import { Directive, ElementRef, Input, OnInit } from '@angular/core'

@Directive({
  selector: '[ttClass]',
})
export class ttClassDirective implements OnInit {

  @Input() ttClass: string;

  constructor(private el: ElementRef) {
  }

  ngOnInit() {
    this.el.nativeElement.classList.add(this.ttClass);
  }

}
Enter fullscreen mode Exit fullscreen mode

Note that we are injecting the ElementRef in the constructor. Whenever we ask for the ElementRef in the constructor, the Angular will inject the reference to the host DOM element of the directive.

ElementRef & XSS Injection Attack

Improper use of ElementRef can result in an XSS Injection attack. For Example in the following code, we are injecting a script using the elementRef. When the component containing such code runs, the script is executed

constructor(private elementRef: ElementRef) {
    const s = document.createElement('script');
    s.type = 'text/javascript';
    s.textContent = 'alert("Hello World")';
    this.elementRef.nativeElement.appendChild(s);
 }
Enter fullscreen mode Exit fullscreen mode

Reference

ElementRef

If you liked this, click the ❤️ below so other people will see this here on Medium. Please don’t forget to like, subscribe and comments.

文章来源:https://dev.to/omamaaslam/elementref-in-angular-how-to-use-it-5039