[スピーカー]Angularは@ViewChildrenを介してリアルタイムでレンダリングされた動的DOMノード要素をどのように取得しますか(@ViewChildは静的な固定DOMノードのみを取得できます)

ストーリーの背景:ある日、Qiang兄弟は動的レンダリングリストコード全体を次のようにコンパイルしました

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つの入力をレンダリングしたいのですが、各入力の値を取得したい場合は、@ ViewChildに従って6つの異なる#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