Reactive Form - Input field focus out automatically - Angular

泪湿孤枕 提交于 2019-12-24 07:26:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!