Angular 400 error PUT when editing only one field

Viewed 58

I have 2 input fields, when I edit only one input and submit I get 400 Error PUT, but when I edit both inputs its allright.
PICTURE OF THE ERROR: https://ibb.co/cbw1QPS
Service component:

  //PUT
    updateBank(data: Ext, id: number) {
        return this.http.put<Ext>('/someData/' + id, data).pipe(
            map(res => {
                return res;
            })
        );
    }

Component Ts

 ngOnInit(): void {
 this.id = this.route.snapshot.params['id'];

    this.myForm = this.fb.group({
      code: [''],
      name: [''],
    });
  }

  //Get by id
  byId() {
    this.itemService.getItemById(this.id).subscribe((res) => {
      return (this.singleS = res);
    });
  }

 //Update
  update() {
    this.singleS.code = this.myForm .value.code;
    this.singleS.name = this.myForm .value.name;
    
    this.banksService
      .updateBank(this.singleS, this.singleS.id)
      .subscribe({
        next: (res: any) => {

        this.showMessage('Updated');
      }, error: (errorMessage) => {
        this.showMessage(errorMessage.errorMessage);
      }});
  }

Component HTML, In my component html I have to get the details from the byId() function and passed in the value section in the html. It updates but only when I edit both inputs, I want to edit only one and when I submit it edits only the one I edited and the other stays the same.

<form [formGroup]="bankForm">
      <label for="code">Code</label>
      <input
        type="text"
        class="form-control"
        id="code"
        formControlName="code"
        [value]="singleS?.code"
      />
      <label for="name">name</label>
      <input
        type="text"
        class="form-control"
        id="name"
        formControlName="name"
        [value]="singleS?.name"
      />
 <button class="btn btn-primary" (click)="update()">Submit</button>
</form>
1 Answers

You are not actually setting any values to your form... so if you do not edit the values in the input, you are sending an empty string. Do NOT use [value] when you are using a reactive form, instead you should set the value in the form (formcontrols) instead.

So when you get the initial values from the backend, you can use patchValue to set the values to the form:

byId() {
  this.itemService.getItemById(this.id).subscribe((res) => {
    this.singleS = res;
    this.myForm.patchValue(res);
  });
}

And in the template, remove value:

  <input
    type="text"
    class="form-control"
    id="code"
    formControlName="code"
  />
  <label for="name">name</label>
  <input
    type="text"
    class="form-control"
    id="name"
    formControlName="name"
  />

And your submit:

update() {
  this.singleS.code = this.myForm.value.code;
  this.singleS.name = this.myForm.value.name;
  this.banksService.updateBank(this.singleS, this.singleS.id)
    //....
}
Related