📜  使用 Angular 获取所有 html 元素数据 - Html (1)

📅  最后修改于: 2023-12-03 15:06:45.103000             🧑  作者: Mango

使用 Angular 获取所有 HTML 元素数据

在 Angular 中,可以使用多种方法获取 HTML 元素的数据。下面将介绍其中的两种方法。

1. 使用 ViewChild 获取单个 HTML 元素数据

ViewChild 是 Angular 中一个用于获取单个 HTML 元素数据的装饰器。例如,若要获取 ID 为 "myInput" 的 input 元素的值,可以将其添加为组件的属性,如下所示:

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

@Component({
  selector: 'app-root',
  template: `<input type="text" #myInput>`,
})
export class AppComponent {
  @ViewChild('myInput')
  myInput: ElementRef<HTMLInputElement>;

  ngAfterViewInit() {
    console.log(this.myInput.nativeElement.value);
  }
}

上述代码中,通过 ViewChild 引用了 DOM 中 ID 为 "myInput" 的元素,并通过 ElementRef 获取了该元素的真实 DOM 元素。然后在 ngAfterViewInit 钩子函数中输出了该元素的值。

2. 使用 ViewChildren 获取多个 HTML 元素数据

ViewChildren 是 Angular 中一个用于获取多个 HTML 元素数据的装饰器。例如,若要获取页面上所有带有 "myClass" 类的 input 元素的值,可以将其添加为组件的属性,如下所示:

import { Component, ViewChildren, QueryList } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <input type="text" class="myClass">
    <input type="text" class="otherClass">
    <input type="text" class="myClass">
  `,
})
export class AppComponent {
  @ViewChildren('myInput')
  myInputs: QueryList<HTMLInputElement>;

  ngAfterViewInit() {
    this.myInputs.forEach((input) => {
      console.log(input.nativeElement.value);
    });
  }
}

上述代码中,通过 ViewChildren 引用了 DOM 中所有带有 "myClass" 类的 input 元素,并通过 QueryList 获取了这些元素的真实 DOM 元素组成的列表。然后在 ngAfterViewInit 钩子函数中遍历了该列表,输出了每个元素的值。

以上就是使用 Angular 获取 HTML 元素数据的两种方法。无论使用哪种方法,都需要注意在指定元素时要使用正确的选择器。同时,若要获取标签内的文本内容,可以通过 innerHTML 或 textContent 属性获取。