[Speaker] How does Angular get real-time rendered dynamic DOM node elements through @ViewChildren (@ViewChild can only get static fixed DOM nodes)

Story background: One day, Brother Qiang compiled the entire dynamic rendering list code as follows

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

  }

}

  

But I want to render 6 inputs, if I want to get the value of each input, I have to name 6 different #input tags according to @ViewChild, which is too tiring, and my list is dynamically rendered in real time (you can add and delete inputs)

So I turned to Angular.cn's https://angular.cn/api/core/ViewChildren https://angular.cn/api/core/ViewChildren

Helpless, brother Qiang has little knowledge and limited understanding. Frankly speaking, he can't understand what the official document says.

I'm still figuring it out 

Finally, I understood the usage of @ViewChildren and changed the code

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)

  }

}

 

Guess you like

Origin blog.csdn.net/qq_37860634/article/details/123943382