import { Component , OnInit } from '@angular/core' ; import { Router , ActivatedRoute } from '@angular/router' ; import { AbstractControlOptions , FormBuilder , FormGroup , Validators } from '@angular/forms' ; import { first } from 'rxjs/operators' ; import { UserService , AlertService } from '@app/_services' ; import { MustMatch } from '@app/_helpers' ; @ Component ( { templateUrl : 'add-edit.component.html' } ) export class AddEditComponent implements OnInit { form ! : FormGroup ; id ! : string ; isAddMode ! : boolean ; loading = false ; submitted = false ; constructor ( private formBuilder , private route , private router , private userService , private alertService ) { } ngOnInit ( ) { this . id = this . route . snapshot . params [ 'id' ] ; this . isAddMode = ! this . id ; const passwordValidators = [ Validators . minLength ( 6 ) ] ; if ( this . isAddMode ) { passwordValidators . push ( Validators . required ) ; } const formOptions = { validators : MustMatch ( 'password' , 'confirmPassword' ) } ; this . form = this . formBuilder . group ( { title : [ '' , Validators . required ] , firstName : [ '' , Validators . required ] , lastName : [ '' , Validators . required ] , email : [ '' , [ Validators . required , Validators . email ] ] , role : [ '' , Validators . required ] , password : [ '' , [ Validators . minLength ( 6 ) , this . isAddMode ? Validators . required : Validators . nullValidator ] ] , confirmPassword : [ '' , this . isAddMode ? Validators . required : Validators . nullValidator ] } , formOptions ) ; if ( ! this . isAddMode ) { this . userService . getById ( this . id ) . pipe ( first ( ) ) . subscribe ( x => this . form . patchValue ( x ) ) ; } } get f ( ) { return this . form . controls ; } onSubmit ( ) { this . submitted = true ; this . alertService . clear ( ) ; if ( this . form . invalid ) { return ; } this . loading = true ; if ( this . isAddMode ) { this . createUser ( ) ; } else { this . updateUser ( ) ; } } private createUser ( ) { this . userService . create ( this . form . value ) . pipe ( first ( ) ) . subscribe ( ( ) => { this . alertService . success ( 'User added' , { keepAfterRouteChange : true } ) ; this . router . navigate ( [ '../' ] , { relativeTo : this . route } ) ; } ) . add ( ( ) => this . loading = false ) ; } private updateUser ( ) { this . userService . update ( this . id , this . form . value ) . pipe ( first ( ) ) . subscribe ( ( ) => { this . alertService . success ( 'User updated' , { keepAfterRouteChange : true } ) ; this . router . navigate ( [ '../../' ] , { relativeTo : this . route } ) ; } ) . add ( ( ) => this . loading = false ) ; } }