20

I am having a little bit of trouble creating my Angular 2 form and converting the submitted data into JSON format for the use of submitting it to my API. I am looking for something that works very similarly to this example: $.fn.serializeObject = function() http://jsfiddle.net/sxGtM/3/
The only problem with this example is that the code is written in JQuery, whereas I'm trying to use strictly angular 2. Any help would be greatly appreciated, I am still very new to angular.

2
  • if you are using angular then why there is no ngmodel in your input? Commented Sep 26, 2016 at 8:59
  • Because this was an example I found, not my code. I want to implement something similar to this example using angular 2 Commented Sep 26, 2016 at 9:15

3 Answers 3

38

You can use the getRawValue() function if you're using a FormGroup, to return an object that can then be serialized using JSON.stringify().

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Http } from '@angular/http';

@Component({
    selector: 'my-component',
    templateUrl: 'my-component.component.html'
})
export class MyComponent implements OnInit {

    form: FormGroup;

    constructor(private fbuilder: FormBuilder,
                private http: Http) { }

    ngOnInit(){
        this.form = this.fbuilder.group({
            name: '',
            description: ''
        });
    }

    sendToAPI(){
        let formObj = this.form.getRawValue(); // {name: '', description: ''}

        let serializedForm = JSON.stringify(formObj);

        this.http.post("www.domain.com/api", serializedForm)
            .subscribe(
                data => console.log("success!", data),
                error => console.error("couldn't post because", error)
            );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

7

You can use JSON.stringify(form.value):

submit() {
  let resource = JSON.stringify(this.form.value);

  console.log('Add Button clicked: ' + resource);

  this.service.create(resource)
    .subscribe(response => console.log(response));
}

Result in Chrome DevTools: Result of console.log

Comments

1

You are looking for JSON.stringify(object) which will give you the JSON represantation of your javascript object.

You can then POST this using the built-in HTTP service to your server.

1 Comment

FormGroups can, and usually do, contain circular references, so this solution would not work unless you customized the stringify function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.