我有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.
}
并且我想专注于选择的下一行。
答案 0 :(得分:1)
更新将子项视为输入或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-select,则需要
<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();
})
}
full stackblitz(在堆叠闪电中,我添加了一个“ takeWhile”以取消订阅ngOnDestroy元素中的更改)
答案 1 :(得分:0)
尝试使用以下代码
<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/programmatically-manage-focus-Angular-app