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");
});
}
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");
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.