Anuj TBE
Anuj TBE

Reputation: 9790

unable to send form data with reative form to api endpoint in angular 6

I'm learning Angular 6 and have created REST API in Django.

I have to send a form data in JSON format to the server.

This is what I'm doing in the component.

my.component.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {AmountGivenService} from '../amount-given.service';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-amount-given-add',
  templateUrl: './amount-given-add.component.html',
  styleUrls: ['./amount-given-add.component.css']
})
export class AmountGivenAddComponent implements OnInit {

  addMoneyForm: FormGroup;
  submitted = false;
  contact_id: string;

  constructor(
    private formBuilder: FormBuilder,
    private amountGivenService: AmountGivenService,
    private route: ActivatedRoute
  ) { }

  ngOnInit(): void {

    this.route.params.subscribe(
      param => {
        this.contact_id = param['contact_id'];
      }
    );

    console.log(this.contact_id);

    this.addMoneyForm = this.formBuilder.group({
      amount: new FormControl('', [
        Validators.required
      ]),
      duration: new FormControl()
    });
  }

  get f() {
    return this.addMoneyForm.controls;
  }

  onSubmit() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.addMoneyForm.invalid) {
      console.log('invalid');
      return;
    }

    console.log(this.addMoneyForm.getRawValue());

    let data = this.addMoneyForm.value;
    data = JSON.parse(data);

    // append contact_id
    data.contact_id = this.contact_id;
    data = JSON.stringify(data);

    this.amountGivenService.add(data).subscribe(res => {
      console.log('req completed', res);
    });
  }

}

before sending the request, I need to append the contact_id.

But on submitting the form, the page is refreshing with form submitted as GET method.

Removing this code elements from above component file is working find and request is being sent to the server.

data = JSON.parse(data);

// append contact_id
data.contact_id = this.contact_id;
data = JSON.stringify(data);

How can I append values to the form data in component?

Edit 2: my.component.html

<form [formGroup]="addMoneyForm" (submit)="onSubmit()" id="form-add-money" #formDir="ngForm">

    <label for="input-amount">Amount</label>
    <input formControlName="amount"
           id="input-amount"
           class="form-control"
           placeholder="Amount">
    <div *ngIf="submitted && f['amount'].invalid" class="text-danger">
        <div *ngIf="f['amount'].errors.required">Amount is required</div>
        </div>
    </div>

    <label for="input-duration">Duration (in days)</label>
    <input formControlName="duration" type="number" id="input-duration" class="form-control" placeholder="Duration (in days)">

</form>

<button class="btn btn-success" type="submit" form="form-add-money" [disabled]="!formDir.valid">
    <i class="fa fa-save">Save</i>
</button>

Upvotes: 0

Views: 1419

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

let data = this.addMoneyForm.value;
data = JSON.parse(data);

// append contact_id
data.contact_id = this.contact_id;
data = JSON.stringify(data);

this.amountGivenService.add(data).subscribe(res => {
  console.log('req completed', res);
});

This makes little sense:

  • the value of a form is not a JSON string. It's an object. Parsing an object makes no sense
  • your amountGivenService should not (and does not, apparently) take a JSON string as argument. It should (and does, apparently) take a typed object.

All you should have is

const data = this.addMoneyForm.value;
data.contact_id = this.contact_id;

this.amountGivenService.add(data).subscribe(res => {
  console.log('req completed', res);
});

Also, in your template, the submit button is outside of the form. It must be inside.

Upvotes: 1

Related Questions