SaschaK
SaschaK

Reputation: 180

Angular multiple form values in ngFor

hope somebody can help me? I'm building a form in my component like this (Version not running):

<div *ngFor="let status of someService.monitoringStatus">
 <form name="form" [formGroup]="form" (ngSubmit)="updateStatus(form.value,status.id)">
  <input type="text" formControlName="next_status" value="{{status.old_status}}">
 </form>
</div>

The problem now is that I can't get {{status.old_status}} in my input as value. But why? If I am using it outside it shows me right.

Edit (my component.ts looks like this):

  form = new FormGroup({
    next_status: new FormControl('', Validators.required)
  })


  updateStatus(value,id: any){
    this.someService.updateStatus(value,id).toPromise().then((data: any) => {  console.log(data)
    }).catch((err: HttpErrorResponse) => {
      console.error('Fehler:', err.error);
    });
  }

Upvotes: 2

Views: 2266

Answers (1)

PMO1948
PMO1948

Reputation: 2554

So you have your forms inside an *ngFor - but they all have the same name, so how can the code distinguish between them? They must all have unique names. If you add an index, you can give them unique names

<div *ngFor="let status of someService.monitoringStatus; let i=index;">
 <form name="form{{i}}" [formGroup]="form{{i}}" (ngSubmit)="updateStatus(form{{i}}.value,status.id)">
  <input type="text" formControlName="next_status{{i}}" value="{{status.old_status}}">
 </form>
</div>

Then you can use {{i}} to distinguish them from each other

Upvotes: 1

Related Questions