关注ngFor内部的输入

Tsc*_*eck 4 focus angular

当用户单击按钮时,addElement方法会将对象推送到数组elements并创建新的输入字段。是否可以专注于新创建的元素?输入没有独特的 ID。

模板:

<div *ngFor="let foo of elements">
  <input class="input" value="{{ foo.value }}" />
</div>
<button (click)="addElement()"></button>
Run Code Online (Sandbox Code Playgroud)

方法:

public addElement() {
  this.elements.push({ value: 'new' });
}
Run Code Online (Sandbox Code Playgroud)

我在此应用程序中使用 Angular 9。

vad*_*mk7 7

您需要通过ViewChildren装饰器查询所有输入,然后每次addElement调用时ngAfterViewChecked也会被调用。因此,您可以使用此钩子来聚焦最后一个已创建的输入。

<div *ngFor="let foo of elements">
  <input 
    #input 
    class="input" 
    [value]="foo.value"
  />
</div>
<button (click)="addElement()"></button>
Run Code Online (Sandbox Code Playgroud)
@ViewChildren('input') inputs: QueryList<ElementRef>;

addElement() {
  this.elements.push({ value: 'new' });
}

ngAfterViewChecked() {
  this.inputs.last.nativeElement.focus();
}
Run Code Online (Sandbox Code Playgroud)

否则,您可以自己检查,不要依赖生命周期挂钩,因为此逻辑ngAfterViewChecked可能会影响您的应用程序中的某些内容:

@ViewChildren('input') inputs: QueryList<ElementRef>;

constructor(private changeDetectorRef: ChangeDetectorRef) {
}

addElement() {
  this.elements.push({ value: 'new' });
  /* run change detection manually to create input element and have access to the last input */
  this.changeDetectorRef.detectChanges();
  this.inputs.last.nativeElement.focus();
}
Run Code Online (Sandbox Code Playgroud)

https://angular.io/api/core/ViewChildren#description

https://angular.io/guide/lifecycle-hooks#lifecycle-event-sequence