baris usanmaz baris usanmaz - 6 days ago 6
TypeScript Question

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.

Answer

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

    <input type="text"
           id="inputUsername"
           name="inputUsername"
           class="form-control"
           placeholder="User Name"
           ngModel
           required>
Comments