【讲人话】Angular如何通过@ViewChildren获取实时渲染的动态DOM节点元素(@ViewChild只能获取静态的固定DOM节点)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                【讲人话】Angular如何通过@ViewChildren获取实时渲染的动态DOM节点元素(@ViewChild只能获取静态的固定DOM节点)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                故事背景:有一天,強哥整了個動態(tài)渲染的列表代碼如下
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標記,這也太累了吧,而且我的列表是動態(tài)實時渲染的(可以添加刪除input)
于是乎我求助Angular.cn的https://angular.cn/api/core/ViewChildrenhttps://angular.cn/api/core/ViewChildren
無奈強哥才疏學(xué)淺、理解能力有限,坦白說,看不懂官方文檔寫的是啥
我還是自己琢磨下?
最后理解了@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);//打印1console.log(this.inputList); //組件對象數(shù)組console.log(this.inputList.toArray()[0].nativeElement.querySelector("input").value); //打印第一個對象的值(打印1)}}
?
總結(jié)
以上是生活随笔為你收集整理的【讲人话】Angular如何通过@ViewChildren获取实时渲染的动态DOM节点元素(@ViewChild只能获取静态的固定DOM节点)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Angular的ChangeDetect
- 下一篇: 【Relax人生法则之躺平方法论】那些看
