![](/img/trans.png)
[英]Angular how to get index from viewChildren queryList items?
[英]How to get specific item in ViewChildren QueryList as ElementRef while filtering on property(ies)?
我試圖在輸入更改后將焦點設置到任何給定輸入(或可能以其他方式操作相同的 DOM 元素)。 我正在使用 Reactive Forms 並且表單元素是動態呈現的。
我遇到的問題是我可以使用@ViewChildren(AppTag) ipt:: QueryList<AppTag>
訪問已更改的元素,這讓我可以過濾我想要的元素,但是我不知道如何抓住它元素使用nativeElement
,或者我可以使用@ViewChildren(AppTag) ipt:: QueryList<ElementRef>
,這(令人驚訝的)似乎讓我過濾有問題的元素,但(同樣令人驚訝的是)我仍然無法操作 DOM元素。 無論哪種方式,我都會收到錯誤: "itm.nativeElement is undefined"
。
要重現錯誤,請在以下StackBlitz中的Inputs
之一中輸入任何值,然后在條目中使用TAB
鍵。 您將在控制台中看到錯誤。
以下是我認為相關的代碼片段,但請使用完整的 StackBlitz 示例以更清楚地查看模板和數據結構:
app.component.ts
export class AppComponent implements OnInit {
@ViewChildren(AppTag) ipt !: QueryList<ElementRef>
name = 'Angular';
formCtls: any = {};
form: FormGroup = new FormGroup({});
data: {} = { // raw data
name:
{
first: {values: [""], label: "first name"},
middle: {values: [""], label: "middle name"},
last: {values: [""], label: "last name"}
}
};
dispData: any[] = []; // Data formatted for display/iteration by template
itmNo: number = 0; // Unique ID for each Input
focusItm = 0; // The bridge by which "FormControl.valueChanges" communicates with "QueryList.changes"
. . .
. . .
ngAfterViewInit() {
this.ipt.changes.subscribe(list=>{
setTimeout(()=>
list.filter(itm=>+itm.id===this.focusItm).forEach(itm=>{
console.log(`Item: ${itm.id} Focus: ${this.focusItm} ${+itm.id===this.focusItm}`);
itm.nativeElement.focus(); // <-- HERE'S WHERE I'M HAVING THE TROUBLE
}
),0)}
)
}
. . .
. . .
renderDisplayArray(){
this.dispData = [];
this.itmNo = 0;
. . .
. . .
const i=r;
this.formCtls[ctlName] = new FormControl(itm["values"][r], {updateOn: 'blur'});
this.form.addControl(ctlName,this.formCtls[ctlName]);
const curItm=this.itmNo;
this.formCtls[ctlName].valueChanges.subscribe(val=>{
console.log(`VALUE: ${val}`);
itm["values"][i]=val || '';
this.renderDisplayArray();
this.focusItm = curItm;
})
. . .
. . .
這是我應用於 Inputs 的 Directive AppTag
,以便能夠filter
和抓取我想要的 DOM 元素。 appTag.ts
import { Component, Directive, ElementRef, OnInit, Input } from "@angular/core";
@Directive({
selector: '[appTag]'
})
export class AppTag implements OnInit{
constructor(private el: ElementRef) {}
@Input('appTag') id: number;
}
只需將 AppTag 中的el: ElementRef
AppTag
可見性更改為 public
@Directive({
selector: '[appTag]'
})
export class AppTag implements OnInit{
constructor(public el: ElementRef) {}
@Input('appTag') id: number;
}
並在您的過濾器 function 中使用AppTag
的el
屬性。
將您的問題行更改為:
itm.el.nativeElement.focus(); // <-- HERE'S WHERE I'M HAVING THE TROUBLE
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.