0

Here I want to send some data on my html form to the backend using angular HTTPClient server. I have used to try this code but not send my data to the backend server.

HTML

 <form class="border text-center p-5 reg-frm" [formGroup]="ContactusForm">
    <label>Full name :</label>
    <input type="text" class="form-control box_border" aria-describedby="textHelp"
                                    name="name" formControlName="name">
    <button (click)="sendMessage()" type="button"
        class="btn btn-info my-4 btn-block reg_btn ">Send Message</button>

 </form>

TS File

sendMessage(){
ContactusForm = this.fb.group({
    name: ['', [Validators.required, Validators.maxLength(100)]],
})

const formData = new FormData();
formData.append('name', this.ContactusForm.value.name)

this.http.post<any>(url, formData).subscribe(res => {
   console.log("data send");
});
}

3
  • @Mridul No, no any errors, Not console log "data send". Commented Jan 13, 2020 at 8:36
  • 1
    Move ContactusForm fb.group declaration to ngOnInit. As per your code ContactusForm.name will be empty for all the times. Commented Jan 13, 2020 at 8:55
  • do not initialize form on button click. that's why your name value is not getting in formData Commented Jan 13, 2020 at 9:02

1 Answer 1

1

This coding practice is not good,do not initialize formGroup inside sendMessage method, instead try this

At first use separate method to initialize form data, for this firstly import FormGroup and other necesssary things required, then declare a formGroup variable/property

import { FormGroup, FormBuilder, Validators } from '@angular/forms';


//declare property
constactUsPayload: FormGroup;

//In Oninit- initialize payload.
ngOnInit(){
  this.initialize_payload();
}

initialize_payload() {
  this.contactUsPayload = this._fb.group({
    'name': this._fb.control('', Validators.required, Validators.maxLength(100)]),
  });//you can declare more fields based on your future requirements
}

sendMessage(){
  this.http.post<any>(url, this.contactUsPayload.value.name).subscribe(res => {
    console.log("data send");
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.