【讲人话】Angular如何通过@ViewChildren获取实时渲染的动态DOM节点元素(@ViewChild只能获取静态的固定DOM节点)

故事背景:有一天,强哥整了个动态渲染的列表代码如下

app.component.html

<div>
    <button (click)="add()">添加一行</button>
    <button (click)="del()">删除一行</button>
</div>

<ul>
    <li *ngFor="let item of items" #input>
        <input type="text" [value]="item">
    </li>
</ul>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})


export class AppComponent {
  constructor() { }

  @ViewChild('input') input: any;

  items = [1, 2, 3, 4, 5, 6];

  add() {
    this.items.push(this.items.length + 1);
  }
  del() {
    this.items.pop();
  }

  ngAfterViewInit() {

    console.log(this.input.nativeElement.querySelector("input").value);//打印1

  }

}

  

但是我要渲染6个input,如果要获取每个input的value,按照@ViewChild的方式我就得命名6个不同的#input标记,这也太累了吧,而且我的列表是动态实时渲染的(可以添加删除input)

于是乎我求助Angular.cn的https://angular.cn/api/core/ViewChildrenhttps://angular.cn/api/core/ViewChildren

无奈强哥才疏学浅、理解能力有限,坦白说,看不懂官方文档写的是啥

我还是自己琢磨下 

最后理解了@ViewChildren的用法,将代码改了下

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})


export class AppComponent {
  constructor() { }

  @ViewChild('input') input: any;
  @ViewChildren('input') inputList!: QueryList<ElementRef>;

  items = [1, 2, 3, 4, 5, 6];

  add() {
    this.items.push(this.items.length + 1);
    setTimeout(() => {
      console.log(this.inputList.toArray()[this.items.length - 1].nativeElement.querySelector("input").value); //打印最新添加的对象值
    }, 0);
  }
  del() {
    this.items.pop();
  }

  ngAfterViewInit() {

    console.log(this.input.nativeElement.querySelector("input").value);//打印1
    console.log(this.inputList); //组件对象数组
    console.log(this.inputList.toArray()[0].nativeElement.querySelector("input").value); //打印第一个对象的值(打印1)

  }

}

 

猜你喜欢

转载自blog.csdn.net/qq_37860634/article/details/123943382