如何聚焦FormArray内部的控件?

时间:2019-08-05 13:43:56

标签: html angular typescript angular-reactive-forms

我有一个带有电子邮件字段的FormArray,每次在FormArray内添加新控件供用户键入电子邮件时,我都需要关注该字段。

我尝试使用@ViewChild,但是它无法正常工作,因为它将重复具有相同ID #emailInput的元素。

component.ts

  public addEmail(): void {
    this.emailArray.push(this.createControlEmail());
    // Here I need to focus on the control that has been added.
    this.form.markAsDirty();
  }

component.html                     

                    <div fxLayout="row" fxLayout.xs="column" fxLayoutAlign="start"
                        [formGroupName]="indexControlEmail">

                        <mat-form-field fxFlex="60" [floatLabel]="true">
                            <input #emailInput matInput placeholder="E-mail" formControlName="email">
                        </mat-form-field>

                        <button mat-icon-button aria-label="delete" matTooltip="Remove email"
                            [matTooltipPosition]="'after'" [matTooltipShowDelay]="1000"
                            (click)="removeEmail(indexControlEmail)">
                            <mat-icon class="secondary-text">close</mat-icon>
                        </button>
                    </div>
                </div>

1 个答案:

答案 0 :(得分:0)

您可以使用ViewChildren来获取页面上的电子邮件输入列表。

  

每当添加,删除或移动子元素时,查询列表   将被更新,并且查询列表中可观察到的更改将   发出新值。

@ViewChildren('emailInput') emailInputs:  QueryList<ElementRef>;

每次addEmail都关注上一封电子邮件输入:

addEmail() {
    this.emailInputs.changes.pipe(take(1)).subscribe({
      next: changes => changes.last.nativeElement.focus()
    });
    this.emailArray.push(this.createControlEmail());
    // const newControl = this.fb.control('');
    // this.emailArray.push(newControl);
  }