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