如何在NGFOR中使用参考ID(#)并获得焦点下一个NG选择



我有loop ngfor,我需要用索引来声明参考ID'#',例如

<button (click)="addRow()"></button>
<tr *ngFor="let data of datas; let i= index">
<td><ng-select #data{{i}} ></ng-select></td>
</tr>
addRow(){
// after selected data next row to focus.
}

我想集中精力到NG-Select的下一行。

使用输入,您可以使用ViewChildren

<div *ngFor="let item of items">
      <input #data/>
</div>
@ViewChildren('data') data: QueryList<ElementRef>;
ngAfterViewInit()
{
    this.data.changes.subscribe(()=>{
       this.data.last.nativeElement.focus();
    })
}

如果我们有ng选择,则需要

<div *ngFor="let item of items">
   <ng-select #data .....>
   </ng-select> 
</div>
<!--see that the "QueryList" is a NgSelectComponent-->
@ViewChildren('data') data: QueryList<NgSelectComponent>;
ngAfterViewInit()
    {
        this.data.changes.subscribe(()=>{
          <!--we use filterInput.nativeElement-->
          this.data.last.filterInput.nativeElement.focus();
        })
    }

一个完整的stackblitz(在stackblitz中,我添加了一个" take take"以取消订阅的变化,ngondestroy element the元素)

尝试使用以下代码

<tr *ngFor="let dataObject of data; let i = index; trackBy:i;">
  <td><ng-select #data{{i}} ></ng-select></td>
</tr>

用于聚焦

import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
... 
@ViewChild('data1') inputEl:ElementRef;
addRow() {
  setTimeout(() => this.inputEl.nativeElement.focus());
}

import Renderer2 from @angular/core into your component. Then:
const element = this.renderer.selectRootElement('#data1');
setTimeout(() => element.focus(), 0);

推荐https://coderanch.com/t/675897/languages/programmatily-manage-focus-angular-angular-app

最新更新