如何在Angular 8的TypeScript文件中通过类名获取所有元素
First, let's fix a critical issue in your template: you’ve added two class attributes to the <label> element, which is invalid HTML. All class names need to be combined into a single class attribute:
<div class="form-group" *ngFor="let item of arr; let i = index"> <label class="name col-sm-2 control-label" [attr.for]="'skillName' + i"> {{ arr[i] }} {{ i }} </label> </div>
Now let’s walk through two ways to access these elements in your TypeScript code:
Approach 1: Direct DOM Access (Your Current Method)
Once the template is fixed, your existing code will work—document.getElementsByClassName returns an HTMLCollection of all elements with the specified class. Note that this collection is "live" (it updates automatically if the DOM changes):
import { Component, AfterViewInit } from '@angular/core'; @Component({ // Your component metadata here (selector, templateUrl, etc.) }) export class YourComponent implements AfterViewInit { arr = ['Skill 1', 'Skill 2', 'Skill 3']; // Example array for context ngAfterViewInit(): void { const nameElements = document.getElementsByClassName('name'); console.log(nameElements); // Logs the HTMLCollection // Iterate over the collection to access individual elements: for (let i = 0; i < nameElements.length; i++) { console.log('Label content:', nameElements[i].textContent); } } }
Approach 2: Angular-Recommended Method (ViewChildren)
For better alignment with Angular’s lifecycle and change detection, use ViewChildren with a template reference variable instead of direct DOM manipulation. This is the more idiomatic approach for Angular:
Update the Template
Add a template reference variable (e.g., #nameLabel) to each label:
<div class="form-group" *ngFor="let item of arr; let i = index"> <label #nameLabel class="name col-sm-2 control-label" [attr.for]="'skillName' + i"> {{ arr[i] }} {{ i }} </label> </div>
Update the TypeScript Code
Use ViewChildren to query all elements with the template reference variable:
import { Component, AfterViewInit, ViewChildren, QueryList, ElementRef } from '@angular/core'; @Component({ // Your component metadata here }) export class YourComponent implements AfterViewInit { arr = ['Skill 1', 'Skill 2', 'Skill 3']; @ViewChildren('nameLabel') nameLabels!: QueryList<ElementRef<HTMLLabelElement>>; ngAfterViewInit(): void { // Access each label element through the QueryList this.nameLabels.forEach(labelRef => { console.log('Label element:', labelRef.nativeElement); console.log('Label text:', labelRef.nativeElement.textContent); }); } }
This method avoids direct DOM access, integrates smoothly with Angular’s change detection, and makes it easier to manage elements as your component evolves.
内容的提问来源于stack exchange,提问作者Code

