问题
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>
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.
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
It gives error Property 'controls' does not exist on type 'AbstractControl'.
Need help on this.
回答1:
Instead of looping over myForm.get('options').value
you shuold loop over myForm.get('options').controls
This should do the trick:
<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>
来源:https://stackoverflow.com/questions/54008466/reactive-form-input-field-focus-out-automatically-angular