1
votes

I have a form with username and password, when a user hits the submit button, a error message is displayed stating if one or both fields are blank, I'm trying to add a route to the button so it takes them to the home page, however, when I add a route to the button, it ignores the validation as aspect and will work if fields are blank. I've tried to disable the button so that it's only enabled when the form is valid but I'm getting a bit confused between ngForm and ngFormModel Thanks This is my html form

<form [ngFormModel]="loginForm" (ngSubmit)="loginUser(loginForm.value)">
<div class="form-group" [ngClass]="{ 'has-error' : !username.valid && submitAttempt }">
   <label class="control-label" for="username">Username</label>
   <em *ngIf="!username.valid && submitAttempt">Required</em>
   <input id="username" type="text" class="form-control" placeholder="Username" ngControl="username">
</div>
<div class="form-group" [ngClass]="{ 'has-error' : !password.valid && submitAttempt }">
   <label class="control-label" for="password">Password</label>
   <em *ngIf="password.hasError('required') && submitAttempt">Required</em>
   <em *ngIf="password.hasError('minlength') && submitAttempt">Must be at least 8 characters</em>
   <input id="password" type="password" class="form-control" placeholder="Password" ngControl="password">
</div>
<div class="form-group">
   <button type="submit" class="btn btn-primary">Register</button>
</div>
</form>

And this is my component

import {Component, EventEmitter} from "angular2/core";
import {Router} from "angular2/router";
import {ROUTER_DIRECTIVES} from "angular2/router";
import {Control, ControlGroup, FormBuilder, Validators, FORM_DIRECTIVES} from 'angular2/common';
//import {UsernameValidators} from './usernameValidators';
@Component({
selector: 'LoginHTML',
templateUrl: 'dev/LoginComponents/login-form.component.html',
directives : [FORM_DIRECTIVES]
})
export class LoginHTMLComponent{
loginForm: ControlGroup;
username: Control;
password: Control;
submitAttempt: boolean = false;
form: ControlGroup;
constructor( private builder: FormBuilder, private _router: Router) {
this.username = new Control('', Validators.required)
this.password = new Control('', Validators.compose([Validators.required, Validators.minLength(8)]))
this.loginForm = builder.group({
username: this.username,
password: this.password
});
}
loginUser(user) {
this.submitAttempt = true;
this._router.navigate(['Dashboard']);
}	
}
1

1 Answers

1
votes

You should be free to do anything with your code, so the form won't try to intervene your loginUser function to navigate to Dashboard. But it does provide you information about form validity that you can make use of:

loginUser(user) {
  this.submitAttempt = true;
  if (this.loginForm.valid) {
    this._router.navigate(['Dashboard']);
  }
}