【问题标题】:how to get html elements created with an ngfor loop如何获取使用 ngfor 循环创建的 html 元素
【发布时间】:2020-08-02 11:30:27
【问题描述】:

大家好这里是我的问题的简化

我使用 *ngfor 在模板中创建了元素

<table >
  <thead>
  <tr>
    <th *ngFor="let item of array" > {{item}}</th>
  </tr>
  </thead>

 </table> 

在 .ts 文件中我有表格

array = [1,2,3,4];

然后当我尝试在控制台中显示元素时

  var cells = document.getElementsByTagName('th'); //or getElementById or anything..
  console.log(cells[1]);

它显示 未定义

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    在 Angular 中,您可以采取不同的方法。

    1) 参考#theadElth 元素之类的,

    <th *ngFor="let item of array" #theadEl> {{item}}</th>
    

    2) 然后在ts 文件中从@angular/core 导入一些类似的东西,

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

    3) 如果我们要获取多个元素,例如,您需要使用 viewChildrenQueryList

     @ViewChildren('theadEl') theadEl: QueryList<ElementRef>
    

    4)然后在ngAfterViewInit生命周期钩子中,可以通过使用来实现,

      ngAfterViewInit(): void {
        const cells = this.theadEl.toArray();
        console.log(cells[1].nativeElement);
        console.log(cells[1].nativeElement.innerHTML);
      }
    

    最后,

    component.html

    <table >
      <thead>
      <tr>
        <th *ngFor="let item of array" #theadEl> {{item}}</th>
      </tr>
      </thead>
     </table> 
    

    component.ts

    import { Component, ViewChildren, ElementRef, QueryList,
      AfterViewInit } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular 4';
    
      array = [1,2,3,4];
    
      @ViewChildren('theadEl') theadEl: QueryList<ElementRef>
    
    
      ngAfterViewInit(): void {
        const cells = this.theadEl.toArray();
        console.log(cells[1].nativeElement);
        console.log(cells[1].nativeElement.innerHTML);
      }
    
    }
    

    Working Stackblitz Here...

    注意:以上是最佳使用实践,但如果你想使用与document.getElementsByTagName('th');相同的方法,那么你需要将代码放入ngAfterViewInit生命周期钩子为像下面的例子。

    Stackblitz with document.getElementsByTagName('th') method

    使用ngAfterViewInit的原因是,它完全初始化了一个组件的视图。

    【讨论】:

      【解决方案2】:

      如果你真的想使用它,document.getElementsByTagName('th'); 也可以在 Angular 中使用。该示例应该可以正常工作,console.log(cells[1]); 将以下内容打印到控制台。

      <th _ngcontent-c0> 2</th> 
      

      如果在您的情况下它导致undefined,则table 在您调用命令时可能尚未创建。我可以想到以下两个可能导致这种情况的原因。

      1. table 包含在当前未包含在文档中的元素中,因为*ngIf 导致false
      2. table 尚未在lifecycle sequence 中创建时,在构造函数中调用该命令。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-26
        • 2020-11-08
        • 1970-01-01
        • 1970-01-01
        • 2020-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多