Solution 1 :

Yes is an ugly, ugly hack

joke apart, as you has the same number of groups in your form array than in your array “listOfPossibleCompaniesFromAPI”(*) just use listOfPossibleCompaniesFromAPI[i]

<form [formGroup]="accountForm">
        <div formArrayName="CompanyArray">
      <div *ngFor="let student of CompanyArray.controls; let i=index" [formGroupName]="i">
          <input type="checkbox" formControlName="selected">
          {{ listOfPossibleCompaniesFromAPI[i] }}
          <input formControlName="specialCode" placeholder="Enter special code">
        </div>
    </div>
</form>

(*)Logically, you has a forEach of this array to push a formGroup in the array

Problem :

I’m relatively new to Angular and I am having an issue with a reactive form/form builder/form array.

Currently, I’m retrieving a list of companies from our API. I need to add an input field to add a ‘special code’ for each company before posting this back.

The issue is that (and examples seem to have led me to this) I am now looping in a loop in order to get the contents of my form control array. Without this companyArray, I am getting errors because Angular is unable to find the form control. ‘form control can not be found -> 0’ etc

I have put in a small hack in the HTML but I am not happy with this at all. I presume the solution is probably quite straightforward and I am doing something fundamentally silly. I am just missing the required knowledge and everything I try seems to break my example. Any help would be most appreciated.

I have created this simplified StackBlitz example below.

StackBlitz EXAMPLE: https://stackblitz.com/edit/angular-267xnc

export class AppComponent {

  listOfPossibleCompaniesFromAPI: any[] = ['BBC', 'Apple', 'Amazon'];
  accountForm: FormGroup;

  ngOnInit() {
    this.accountForm = this.fb.group({
      'CompanyArray': this.fb.array([])
    });
    this.listOfPossibleCompaniesFromAPI.forEach(() => {
      this.CompanyArray.push(this.fb.group(new Group(false, '')));
    });
  }

  constructor(private fb: FormBuilder) {}

  get CompanyArray(): FormArray {
    return this.accountForm.get('CompanyArray') as FormArray;
  }
}
<form [formGroup]="accountForm">
  <div *ngFor="let companyName of listOfPossibleCompaniesFromAPI; let z=index">
    <div formArrayName="CompanyArray">
      <div *ngFor="let student of CompanyArray.controls; let i=index" [formGroupName]="z">
        <div *ngIf="z === i">
          <input type="checkbox" formControlName="selected"> {{ companyName }}
          <input formControlName="specialCode" placeholder="Enter special code">
        </div>
      </div>
    </div>
  </div </form>

  {{accountForm.value | json}}

Comments

Comment posted by Chellappan வ

You mean without looping listOfPossibleCompaniesFromAPI array you getting error?

By

Leave a Reply

Your email address will not be published. Required fields are marked *