反应形式-输入字段自动聚焦-角度 [英] Reactive Form - Input field focus out automatically - Angular
问题描述
我有一个奇怪的问题. 演示
I am having strange issue. Demo
.ts
import { Component } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.myForm = this.formBuilder.group({
'options': this.formBuilder.array([this.createOption()])
});
}
createOption(): FormGroup {
return this.formBuilder.group({
'name': [null]
});
}
}
.html
<form novalidate [formGroup]="myForm" >
<div formArrayName="options" class="mt-3">
<div [formGroupName]="i" *ngFor="let option of myForm.get('options').value; let i = index;">
<input id="{{'name' + i}}" autocomplete="off" type="text" class="form-control" aria-label="Name"
formControlName="name">
</div>
</div>
</form>
我有一个包含多个选项name
字段的表单.在html中,我对每个选项都有循环以显示字段.现在,如果我在输入字段中输入任何字符,它将自动聚焦到该字段之外.
I have a form which has multiple options' name
field. In html I have loop for each options to show fields. Now if I enter any character in the input field, it automatically focus out of the field.
如果将*ngFor="let option of myForm.get('options').value; let i = index;"
更改为*ngFor="let option of myForm.get('options').controls; let i = index;"
-它可以解决此问题.
If I change *ngFor="let option of myForm.get('options').value; let i = index;"
to *ngFor="let option of myForm.get('options').controls; let i = index;"
- it solves the issue.
但是,如果我尝试将其部署到生产环境中并运行
But if I try to deploy it on production and I run
ng build --prod
它给出错误Property 'controls' does not exist on type 'AbstractControl'.
对此需要帮助.
推荐答案
您无需在myForm.get('options').value
上循环,而应该在myForm.get('options').controls
Instead of looping over myForm.get('options').value
you shuold loop over myForm.get('options').controls
这应该可以解决问题:
<form novalidate [formGroup]="myForm" >
<div formArrayName="options" class="mt-3">
<div [formGroupName]="i" *ngFor="let option of myForm.get('options').controls; let i = index;">
<input id="{{'name' + i}}" autocomplete="off" type="text" class="form-control" aria-label="Name" formControlName="name">
</div>
</div>
</form>
<form novalidate [formGroup]="myForm" >
<div formArrayName="options" class="mt-3">
<div [formGroupName]="i" *ngFor="let option of myForm.get('options').controls; let i = index;">
<input id="{{'name' + i}}" autocomplete="off" type="text" class="form-control" aria-label="Name" formControlName="name">
</div>
</div>
</form>
这篇关于反应形式-输入字段自动聚焦-角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!