Angular2 ngForm not working

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

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

Everything seems normal, but the form data does not come to the 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.

+5
source share
1 answer

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

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

Source: https://habr.com/ru/post/1260452/


All Articles