I\'m trying to post data from a small registration form to the server
I\'ve been stuck in this since three days now i don\'t know how to do it, i\'m still beginner i
Why not using reactive forms from Angular? What you are doing seems a lot complicated for no reason.
Please read: Angular Reactive Forms. That should give you enough information on how to work with forms.
Once you define form controls you can subscribe to valueChanges and react accordingly, while still having access to form (and control) values.
This is how you do it. stackblitz
The component
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { NgForm } from '@angular/forms';
import {HttpClient,HttpErrorResponse} from '@angular/common/http';
declare const $;
@Component({
selector: 'app-add-account',
templateUrl: './add-account.component.html',
//styleUrls: ['./add-account.component.css'],
encapsulation: ViewEncapsulation.None
})
export class AddAccountComponent implements OnInit {
name: any[];
password: any[];
email: any[];
userNames: any[];
private url = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) {
}
ngOnInit(){
}
// userName(input: HTMLInputElement) {
// let user = {name: input.value};
// debugger;
// //input.value = '';
// this.http.post(this.url, JSON.stringify(user))
// .subscribe(response => {
// alert(response);
// },(err: HttpErrorResponse) => {
// alert(err);
// });
// }
onSubmit(form: NgForm){
var data = form.value;
debugger;
var myPostObject = {
firstName:data.firstname,
lastName:data.lastname,
email:data.email,
passWord:data.password,
}
this.http.post(this.url, myPostObject)
.subscribe(response => {
debugger;
console.log(response);
},(err: HttpErrorResponse) => {
console.log(err);
});
}
}
The HTML
<form #registerForm="ngForm" >
<div class="row col-md-12">
<input name="firstname" ngModel #firstname="ngModel" type="text"
class="rounded-inputs25 col-md-3 first-name-input add-account-inputs"
placeholder="First name" >
<input type="text" name="lastname" ngModel #lastname="ngModel" class="rounded-inputs25 col-md-3 last-name-input
add-account-inputs" placeholder="Last name" >
</div>
<input type="email" name="email" ngModel #email="ngModel" class="rounded-inputs25 col-md-6 add-account-
inputs" placeholder="Email" >
<input type="password" name="password" ngModel #password="ngModel" class="rounded-inputs25 col-md-6 add-account-
inputs" id="password" placeholder="Password" >
<input type="password" (keyup.enter)="onSubmit(registerForm)" class="rounded-inputs25 col-md-6 add-account-
inputs" id="confirm_password" placeholder="Confirm password" >
</form>