2

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);
    });
  }
2
  • 1
    Why is the form element inside the *ngFor loop? You are creating as many form elements as the status count. Commented Dec 3, 2020 at 6:10
  • That is right. I need solution to send forms based of ngFor. Commented Dec 3, 2020 at 12:06

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Hi, thanks for reply my question. I thought about this solution before. But how does my component.ts has to look like with form = new FormGroup({ .... ??
declare your forms as form0, form1,... If you include you ts code, I could help you with syntax based on what you have
where do you get someService.monitoringStatus from? Is it an array? What is its type? In theory, you can make an array of forms, then if someService.monitoringStatus gives an array, run a foreach on it where you add another new form to the array. And then in HTML, forms[i] instead of form{{i}}
I created a repo which describes problem perfectly. github.com/sascha284/forms
the link is broken

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.