Unable to check for error on the HTML DOM for Angular Reactive From CustomValidator

52 views Asked by At

I am trying to create a custom validator for an Angular reactive form that checks for the existence of a username in a Firestore database. The validator is working as expected and returning the expected error object, but I am having trouble displaying the error message in the HTML DOM.

Here's my custom validator class:

export class CustomValidator {
  static username(firestore: Firestore) {
    return async (control: AbstractControl) => {
      const username = control.value;
      const docRef = doc(firestore, 'usernames', username);
      const docSnap = await getDoc(docRef);
      console.log(docSnap.exists());
      return docSnap.exists() ? { usernameTaken: true } : null;
    };
  }
}

my ts file:

import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators,
} from '@angular/forms';
import { doc, Firestore, getDoc } from '@angular/fire/firestore';

form!: FormGroup;

constructor(private firestore: Firestore) {}

ngOnInit(): void {
    this.form = this.fb.group({
      username: [
        '',
        [
          CustomValidator.username(this.firestore),
        ],
      ],
    });
}

And here's my template code:

<form [formGroup]="form">
  <input type="text" formControlName="username">
  <div *ngIf="form.get('username').hasError('usernameTaken')">
    <div class="alert alert-danger">
      This username is already taken
    </div>
  </div>
</form>

The problem is that the error message is not displayed in the HTML DOM. Can anyone help me understand what I am doing wrong?

0

There are 0 answers