0

Im trying to print content of input field in the form of angular2 but getting object at the console as result (myform type of ControlGroup), here is my code look like, why this happens actually

import { FORM_DIRECTIVES, ControlGroup, AbstractControl, 
FormBuilder, Validators} from 'angular2/common';


@Component({
  selector : 'formbuilder',
  template : `
    <h1> FOrm Using Formbuilder </h1>
    <form  [ngFormModel] = "myform" (ngSubmit) = "onSubmit(myform.value)">
      <lable>Name: </lable>
      <input type = "text" [ngFormControl] = "myform.controls['input1']" />
      <input type = "text" [ngFormControl] = "myform.controls['input2']" />
      <button type = "text">Submit</button>  
    </form>
  `,
  directives : [FORM_DIRECTIVES]
})
export class formbuilder {
  myform : ControlGroup ;
  ac : AbstractControl;
  constructor(fb : FormBuilder) {
    this.myform = fb.group({
      'input1' : ['ABC', Validators.required],
      'input2' : ['DEF', Validators.required]
    }); 
    this.ac = this.myform.controls['ac']
  }

  onSubmit(value : any) : void {
    console.log("submit method called "  + value);
  }
}
bootstrap(formbuilder);
1
  • 2
    Why do you think myform.value will give you the value of a text field? You're literally asking for the value of the entire form. Commented Feb 23, 2016 at 16:46

1 Answer 1

2

I have just tested your code and myForm.value contains the following:

{input1: "ABC", input2: "DEF"}

This corresponds to the value of all controls you defined.

If you want to input of a particular field you can use this:

this.myform.controls.input1.value;
Sign up to request clarification or add additional context in comments.

4 Comments

yes, but why it has to happen object written on console
If you only put console.log(value);, you will be able to introspect the object in the console and that it only has properties input1 and input2...
You can also use console.log(JSON.stringify(value));
You have always been amazing to me!

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.