MMR
MMR

Reputation: 3009

http in angular 2.0 post

How can I add my form data to my db using http, well I tried doing this but caught at an error, can someone do it.

My template

    <h1>Address Form</h1>

     <div class="alert alert-info" role="alert">
Error messages per field and disabled save button until entire form is valid.
    </div>
          <form (ngSubmit)="onSubmit(myForm.value)" #myForm="ngForm">
    <div class="form-row">
    <div class="formHeading">First Name</div>
    <input type="text" id="firstName" ngControl="firstName">

   </div>

   <div class="form-row">
    <div class="formHeading">Street Address</div>
    <input type="text" id="firstName" ngControl="streetAddress">

   </div>

   <div class="form-row">
    <div class="formHeading">Zip Code</div>
    <input type="text" id="zip" ngControl="zip">

   </div>

   <div class="form-row">
    <button type="submit" >Save</button>
   </div>

</form>

My component

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

   import {FormBuilder, Validators, ControlGroup, FORM_DIRECTIVES}  from '@angular/common';

 @Component({

    templateUrl: './components/address-form/address-form.html',
    directives: [FORM_DIRECTIVES],
}) 
 export class AddressForm {
 onSubmit(form:any):void {
  console.log(form);

}
   }

This is what I have done so far, can anyone suggest what I should do more since I am not able to see anything in db.

Upvotes: 0

Views: 217

Answers (1)

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

Change your form tag to this:

<form (ngSubmit)="onSubmit(myForm.controls)" #myForm="ngForm">

and in your onSubmit() method this should work:

onSubmit(form) {
    console.log(form.firstName);
    console.log(form.lastName);
    console.log(form.phone);

    // ...
}

Upvotes: 1

Related Questions