Search code examples
angularformsreactiveformarray

Reactive Forms | FormArray Runtime Control Issue | Angular 15


I am new to angular. I wrote one code to dynamically add controls and delete controls using delete button. It is working fine. But at runtime I am able to input only one character in the controls that render in the browser initially and after pressing add button. It is not showing any runtime/compile time error.

Can Anyone help me.

//html File Code


 <form [formGroup]="regform">
  <div formArrayName="details">
    <div
      *ngFor="let d of regform.controls.details.value; let i = index"
      [formGroupName]="i"
    >
      <input
        type="text"
        placeholder="Enter Full Name"
        formControlName="fullName"
      />
      &nbsp;

      <input
        type="text"
        placeholder="Enter Roll Number"
        formControlName="rollNumber"
      />
      &nbsp;

      <input
        type="text"
        placeholder="Enter Class Details"
        formControlName="class"
      />&nbsp;

      <input
        type="text"
        placeholder="Enter Mobile Number"
        formControlName="mobileno"
      />&nbsp;

      <button
        style="
          background-color: #f44336;
          padding: 14px 20px;
          margin: 8px 0;
          border: none;
          cursor: pointer;
          opacity: 0.9;
        "
        (click)="deleteRow(i)"
      >
        X
      </button>
    </div>
  </div>
</form>

<br />

<div>
  <button
    style="
      background-color: #04aa6d;
      padding: 14px 20px;
      margin: 8px 0;
      border: none;
      cursor: pointer;
      opacity: 0.9;
    "
    (click)="addcontrol()"
  >
    Add
  </button>
</div>

// TS File Code is below

  @Component({
  selector: 'app-hwreactiveform',
  templateUrl: './hwreactiveform.component.html',
  styleUrls: ['./hwreactiveform.component.css'],
})
export class HwreactiveformComponent {
  regform: FormGroup;

  constructor(private _fb: FormBuilder) {}

  ngOnInit(): void {
    this.regform = this._fb.group({
      details: this._fb.array([this.buildcontrol()]),
    });
  }

  buildcontrol() {
    return this._fb.group({
      fullName: [''],
      rollNumber: [''],
      class: [''],
      mobileno: [''],
    });
  }

  addcontrol() {
    const cont = <FormArray>this.regform.controls['details'];
    cont.push(this.buildcontrol());
  }

  deleteRow(index: any) {
    (<FormArray>this.regform.controls['details']).removeAt(index);
  }
}

Solution

  • Here is the stackblitz for you https://stackblitz.com/edit/angular-r9dylb?file=src%2Fmain.ts

    The problem is that you use a formControlValue for your *ngFor.

    let d of regform.controls.details.value !!!
    

    FormValue change when your input change value, as you type in your input (input event). Therefore your UI always re-render when it have any new input, that makes your forcus is out. Just make sure your UI just re-render when you click on button.