How to post the Form data using template driven forms using angular 4

1.1k views Asked by At

I want to post the request payload data on submit the form fields as post API: Facing issue with the 400 bad request.

How to pass the request payload with the form details?

component.html

<form #RequestForm="ngForm" (ngSubmit)="onSubmit(RequestForm.value)" novalidate>
  <div class="row form-group">
    <div class="col-xs-12">
      <label for="title">Request Title <span class="required-field"> *</span></label>
      <input type="text" class="form-control" id="title" name="title" required [(ngModel)]="StudentRequest.title" #titleControl="ngModel" minlength="1" maxlength="255">
    </div>
    <div class="row form-group">
      <div class="col-xs-12">
        <label for="description">description <span class="required-field"> *</span></label>
        <textarea rows="5" cols="20" class="form-control" id="description" name="description" [(ngModel)]="Request.description" #descriptioncontrol="ngModel" required minlength="1" maxlength="3000"></textarea>
        <div *ngIf="descriptioncontrol.invalid && descriptioncontrol.dirty && descriptioncontrol.touched" class="alert-error">Must be between 1 and 255 characters.</div>
      </div>
      <button class="btn btn-primary" (keyup.enter)="onSubmit()" value="onSubmit()" [disabled]="`enter code here`RequestForm.invalid">Submit Request</button>
    </div>

</form>

component.ts

export class AppComponent implements OnInit {
  StudentRequest = {};

  ComplaintRequest() {

  }
}

Service.ts

public studentComplaintRequest(request: ComplaintRequest): Observable < HttpResponse < string >> {

  const RequestUrl = //API
  const methodName: string = `${this.serviceName}.studentComplaintRequest`;

  return this.http.post(RequestUrl, {
    headers
  }).map((data: any) => {
    if (data) {
      this.logger.
      debug(`${methodName}: data returned from api call.`);
      return data;
    } else {
      throw new Error(`${methodName}: No data returned from api call`);
    }
  });
}
1

There are 1 answers

0
Skatt On

You can use with the form html tag the properties [form] and [formGroup], like this.

<form [form]="myForm" [formGroup]="myForm" (ngSubmit)="onSubmit()">
<input [formControlName]="firstItemForm">
<input [formControlName]="secondItemForm">
</form>

And in your ts you need

ngOnInit(){
this.myForm = new FormGroup({
    firstItemForm: value, Validators.required,
    secondItemForm: value, Validators,required
    })
}

onSubmit(){
this.myForm // have all the data and then you can manage the http petition after

}