Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 ngForm not working

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.

like image 680
baris usanmaz Avatar asked Nov 28 '16 13:11

baris usanmaz


1 Answers

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>
like image 145
philipooo Avatar answered Nov 14 '22 12:11

philipooo