【问题标题】:How to focus a control that is inside a FormArray?如何聚焦 FormArray 内的控件?
【发布时间】:2019-12-13 01:19:04
【问题描述】:

我有一个带有电子邮件字段的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>

【问题讨论】:

    标签: html angular typescript angular-reactive-forms


    【解决方案1】:

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

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

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

    每次addEmail关注最后一个emailInput:

    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);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 2014-08-30
      • 2020-08-16
      • 2023-02-17
      • 2021-04-27
      相关资源
      最近更新 更多