Computer Science, asked by Arun7005, 1 year ago

How to get form data into json while clik on submit in angular2?

Answers

Answered by clue
0

In Angular 2+ we handle forms two ways:


Template-driven

Reactive

Here is some code for simple template-driven forms.


Your module file should have these:


import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'

import { ReactiveFormsModule, FormsModule } from '@angular/forms';

import { MyApp } from './components'


@NgModule({

 imports: [

   BrowserModule,

   FormsModule,

   ReactiveFormsModule

 ],

 declarations: [MyApp],

 bootstrap: [MyApp]

})

export class MyAppModule {


}


platformBrowserDynamic().bootstrapModule(MyAppModule)

Simple registration html file:


<form #signupForm="ngForm" (ngSubmit)="registerUser(signupForm)">

 <label for="email">Email</label>

 <input type="text" name="email" id="email" ngModel>


 <label for="password">Password</label>

 <input type="password" name="password" id="password" ngModel>


 <button type="submit">Sign Up</button>

</form>

Now your registration.ts file should be like this:


import { Component } from '@angular/core';

import { NgForm } from '@angular/forms';


@Component({

 selector: 'register-form',

 templateUrl: 'app/register-form.component.html',

})

export class RegisterForm {

 registerUser(form: NgForm) {

   console.log(form.value);

   // {email: '...', password: '...'}

   // ... <-- now use JSON.stringify() to convert form values to json.

 }

}

To handle this data on server side use this link: https://stackoverflow.com/questions/41154319/how-to-post-json-object-with-http-post-angular-2-php-server-side

I think this is more than sufficient.

Similar questions