angularangular-formsangular-controller

Angular - pass additional form data to the server


I have a basic Angular form with prod_name, prod_desc, prod_price, those of course I want to send to the server when form is submitted.

However I want to send additional peace of data and I don't want to make hidden input field for that.

So stripped version of form looks something like this:

<form [formGroup]="productForm" (ngSubmit)="onFormSubmit(productForm.value)">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Product Name" formControlName="prod_name"
           [errorStateMatcher]="matcher">

  </mat-form-field>

 <!-- Additional two form fields omitted for clarity -->

  <div class="button-row">
    <button type="submit" [disabled]="!productForm.valid" mat-flat-button color="primary"><mat-icon>save</mat-icon></button>
  </div>
</form>

Basically it invokes onFormSubmit() and passes to it productForm.value.

This is what controller looks like, stripped with only necessary data for clarity:

@Component({
//...
})
export class ProductAddComponent implements OnInit {

  productForm: FormGroup;
  updated_at: Date = null;

  constructor(private router: Router, private api: ApiService, private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.productForm = this.formBuilder.group({
      'prod_name' : [null, Validators.required],
      'prod_desc' : [null, Validators.required],
      'prod_price' : [null, Validators.required]
    });
  }

  onFormSubmit(form: NgForm) {
    // Here I want to add current date as well to the form data before sending it
    this.api.addProduct(form)
      .subscribe(res => {
          let id = res.id;
          this.router.navigate(['/product-details', id]);
      }, err => {
          console.log(err);
      });
  }

}

Within onFormSubmit() function I want to pass a current date to the server as well.
Hidden field in the form template is not the option.
I want to do it in the onFormSubmit() function before calling the service but I'm stuck.

I would appreciate help as to how basically set additional data along with the form data, for example date and sent it to the server.


Solution

  • You can copy the form data and then add anything you want to it.

      onFormSubmit(form: NgForm) {
        const dataForSubmit = {...form.value}; // copies the form data into a new variable
        dataForSubmit.otherProperty = 'what ever you want'; // add whatever data is needed
        this.api.addProduct(dataForSubmit)
          .subscribe(res => {
              let id = res.id;
              this.router.navigate(['/product-details', id]);
          }, err => {
              console.log(err);
          });
      }
    

    In my applications, I often have an interface defined for all of the data. I get that data into that interface and only copy the fields I want to the form. Then on a save, copy the changes from the form onto the original object.

    Interface

    export interface Product {
      id: number;
      productName: string;
      productCode: string;
    }
    

    Of course, the system id does not appear in the UI.

    Component code

    // Update the data on the form
    // after a get
    this.productForm.patchValue({
      productName: this.product.productName,
      productCode: this.product.productCode
    });
    
    // The save
      saveProduct(): void {
        if (this.productForm.valid) {
           // Copies any changed form values over the original product values
           const p = { ...this.product, ...this.productForm.value };
    
           // Call the http service put to save the data `p`
        }
      }