Create an Account Component

mail@pastecode.io avatar
unknown
typescript
2 years ago
1.6 kB
15
Indexable
Never
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { AbstractControl, AsyncValidatorFn, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { map } from 'rxjs';
import { UsersService } from 'src/app/services/users.service';

@Component({
  selector: 'app-create-an-account',
  templateUrl: './create-an-account.component.html',
  host: { class: 'login-box'},
  encapsulation: ViewEncapsulation.None,
  styleUrls: ['./create-an-account.component.scss']
})
export class CreateAnAccountComponent implements OnInit {

  createUserForm!: FormGroup;

  constructor(
    private usersService: UsersService,
    private fb: FormBuilder
  ) { }

  ngOnInit(): void {
    this.createUserForm = this.fb.group({
      username: ['', Validators.required],
      email: ['', {
        validators: [Validators.required],
        
        asyncValidators: [this.userExistsValidator(this.usersService)]
      }],
      password: ['', Validators.required],
      
    })
    this.createUserForm.controls['email'].setErrors({ userExists: true });
  }

  get email() {
    return this.createUserForm.get('email');
  }
  get password() {
    return this.createUserForm.get('password');
  }


  userExistsValidator(usersService: UsersService): AsyncValidatorFn  {
    return (control: AbstractControl) => {
      return usersService.findUserByEmail(control.value)
        .pipe(
            map(user => user ? {userExists:true} : null)
        );
    }
  }


  onCreateUser() {

  }


}