Martin Kostadinov
Martin Kostadinov

Reputation: 51

Can't send changed data from *ngFor generated form with inputs of object type

I have a problem with a form. I have a JSON object which includes some data and in HTML form I use ngFor to set every input tag in this form to have as value one of every value in this JSON.

The problem is that I won't after this when one of this inputs data change and the send button is clicked (its not necessary to have changes in the inputs values) all values to be stored back in the object and send to a method to console.log them.

The form template is:

    <form class="example-form"  style="margin-left: 500px;">
      <mat-form-field class="example-full-width" *ngFor=" let item of test | keyvalue">
        <input matInput placeholder="{{item.key}}" value="{{item.value}}" name="" >

      </mat-form-field>

      <button type="submit" (click)="send()">Send</button>

    </form>
    async ngOnInit() {

        this.test= await this.authService.getMultilingual('au');
    }

Upvotes: 0

Views: 114

Answers (2)

SiddAjmera
SiddAjmera

Reputation: 39432

Sounds like a perfect use case for a Reactive Form. Just create a Reactive Form around the Data Model.

Let's say you have some data model like this:

export interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

which is for the data that you're getting from JSONPlaceholder for eg.

You can generate a Reactive Form around it:

private generateTodoListForm(todo: Todo) {
  return this.fb.group({
    userId: [todo.userId],
    id: [todo.id],
    title: [todo.title],
    completed: [todo.completed]
  });
}

And then use it in your template:

<div *ngIf="(todoForm$ | async) as todoForm">
  <form [formGroup]="todoForm" (submit)="onSubmit(todoForm.value)">
    <label for="userId">User Id</label>
    <input name="userId" type="text" formControlName="userId">
    <br>
    <label for="id">Id</label>
    <input name="id" type="text" formControlName="id">
    <br>
    <label for="title">Title</label>
    <input name="title" type="text" formControlName="title">
    <br>
    <label for="completed">Completed</label>
    <input name="completed" type="checkbox" formControlName="completed">
    <br>
    <button type="submit">Submit</button>
  </form>
</div>

Here's a Working Sample StackBlitz for your ref.

Upvotes: 0

gavgrif
gavgrif

Reputation: 15509

Should you not be using ngModel? - that way you are binding the value in the json to the value of the input and subsequently changing the input value results in changing the data vale that you send?

<input matInput placeholder="{{item.key}}" [(ngModel)]="item.value" name="" >

Upvotes: 1

Related Questions