1

I have an edit form as below which contains data in the input fields.

<ng-form #infoForm="ngForm" novalidate>
            <div>
                <label for="firstName">First Name :</label>
                <input type="text"
                       class="form-control"
                       id="firstName"
                       name="firstName"
                       [(ngModel)]="in.firstName">
            </div>
            <div>
                <label for="lastName">Last Name :</label>
                <input type="text"
                       autocomplete="on"
                       class="form-control"
                       id="lastName"
                       name="lastName"
                       [(ngModel)]="in.lastName">
            </div>
<button type="button" class="btn btn-primary" (click)="updateInfo(infoForm.value)">Update
                </button>
    </ng-form>

And I have the function in the component as below:

updateInfo(info: any) {
        console.log(info);
}

This form return all the values (to the console) in the form when the Update button clicked, but I want to submit only the edited values instead of whole form. How could I implement it?

1 Answer 1

4

For this you can pass the form instead of its value to 'updateInfo' function and process it there. If user change the control value its state becomes 'dirty' from 'touched/pristine' and we can filter controls based on that.

Change in html:

<button type="button" class="btn btn-primary" (click)="updateInfo(infoForm)">Update
        </button>

Change in *.ts file:

updateInfo(info: NgForm) {
    const changedValues = Object.keys(info.controls)
      .filter(key => info.controls[key].dirty === true)
      .map(key => {
        return { control: key, value: info.controls[key].value }
      });
    console.log(changedValues);
  }
Sign up to request clarification or add additional context in comments.

2 Comments

How could I build it in an array? e.g: {firstName: "john", lastName: "sam"}
Just update the return object inside map as you need.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.