import { Component , OnInit } from '@angular/core' ; import { FormArray , FormBuilder , FormControl , FormGroup , Validators } from '@angular/forms' ; import { StaffService } from '../model/staff.service' ; import { Router } from '@angular/router' ; @ Component ( { selector : 'app-login' , templateUrl : './login.component.html' } ) export class LoginComponent implements OnInit { loginForm : FormGroup ; formErrors : any ; submitted : boolean = false ; errorMessage : string = '' ; today : Date ; constructor ( private staffService , private router , private formBuilder ) { this . today = new Date ( ) ; this . loginForm = formBuilder . group ( { username : [ '' , Validators . required ] , password : [ '' , Validators . compose ( [ Validators . required , Validators . minLength ( 6 ) ] ) ] } ) ; this . loginForm . valueChanges . subscribe ( data => this . onValueChanged ( data ) ) ; } setFormErrors ( errorFields ) { for ( const key in errorFields ) { if ( ! errorFields . hasOwnProperty ( key ) ) { continue ; } const message = errorFields [ key ] ; this . formErrors [ key ] . valid = false ; this . formErrors [ key ] . message = message ; } } resetFormErrors ( ) { this . formErrors = { username : { valid : true , message : '' } , password : { valid : true , message : '' } } ; } isValid ( field ) { let isValid = false ; if ( this . loginForm . controls [ field ] . touched === false ) { isValid = true ; } else if ( this . loginForm . controls [ field ] . touched === true && this . loginForm . controls [ field ] . valid === true ) { isValid = true ; } return isValid ; } public onValueChanged ( _data ? ) { if ( ! this . loginForm ) { return ; } const form = this . loginForm ; for ( const field of Object . keys ( this . formErrors ) ) { const control = form . get ( field ) ; if ( control && control . dirty ) { this . formErrors [ field ] . valid = true ; this . formErrors [ field ] . message = '' ; } } } ngOnInit ( ) { this . resetFormErrors ( ) ; this . staffService . logout ( ) ; } getFormControls ( key ) { return this . loginForm . get ( key ) as FormControl ; } public onSubmit ( elementValues ) { this . submitted = true ; this . staffService . login ( elementValues . username , elementValues . password ) . subscribe ( result => { if ( result . success ) { this . router . navigate ( [ '/dashboard' ] ) ; } else { this . errorMessage = 'Username or password is incorrect.' ; this . submitted = false ; } } , error => { this . submitted = false ; if ( error . status === 422 ) { this . resetFormErrors ( ) ; this . setFormErrors ( JSON . parse ( error . data . message ) ) ; } else { this . errorMessage = error . data ; } } ) ; } }