6

I am trying to do a login form component but I cannot read the form data.

When I try to write username on the console, 'undefined' writes.

Everything seems usual but form data does not come to component.

Below is the html code:

<form (ngSubmit)="onSubmit(myForm)"
      #myForm="ngForm"
      class="form-signin">
    <div class="form-group">
        <h2 class="form-signin-heading">Please sign in</h2>
        <input type="text"
               id="inputUsername"
               name="inputUsername"
               class="form-control"
               placeholder="User Name"
               required>
        <input type="password"
               id="inputPassword"
               name="inputPassword"
               class="form-control"
               placeholder="Password" >
    </div>
    <button class="btn btn-lg btn-primary btn-block"
            type="submit">Sign in</button>
</form>

Component ts:

@Component({
    selector: 'signin',
    templateUrl: './signin.component.html',
    encapsulation: ViewEncapsulation.None
})
export class SigninComponent implements OnInit{
    constructor(){}

    ngOnInit(){ }

    onSubmit(form: NgForm){
        console.log(form.value.inputUsername);
    }
}

Thanks in advance.

2
  • 1
    I don't think the styles are relevant to the problem :D Commented Nov 28, 2016 at 13:12
  • Ok, I deleted styles. Commented Nov 28, 2016 at 13:13

2 Answers 2

9

You need to add the ngModel directive to each of the form fields. This registers the form fields to your form.

    <input type="text"
           id="inputUsername"
           name="inputUsername"
           class="form-control"
           placeholder="User Name"
           ngModel
           required>
Sign up to request clarification or add additional context in comments.

2 Comments

I am a newbie on Angular2 and I did not know this requirement. Thank you, this is the right answer.
You are welcome! Here are some further readings angular.io/docs/ts/latest/api/forms/index/NgForm-directive.html
0

add FormsModule in appmodule.ts

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

imports: [ FormsModule, ]

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.