'Angular creating custom reactive form validator

I created simple ValidatorFn function:

  requiredArrayLength(length: number): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      if (length >= 1) {
        return null;
      }
      else
        return { 'requiredArrayLength': true };
    }
  }

and i'm trying use this by my formControl:

  createClientForm = new FormGroup({
    redirectUris: new FormControl(null, [this.requiredArrayLength(this.redirectUris.length)]),
    allowedScopes: new FormControl(null, [this.requiredArrayLength(this.allowedScopes.length)]),
    postLogoutUris: new FormControl(null, [this.requiredArrayLength(this.postLogoutUris.length)])
  });

These arrays aren't empty, because their values are successfully displayed in my mat-chip-list:

<mat-form-field appearance="fill" color="accent" class="field">
                <mat-label>Redirect URIs</mat-label>
                <mat-chip-list #redirectUrisList formControlName="redirectUris">
                    <mat-chip class="chip" *ngFor="let redirectUri of redirectUris"
                        (removed)="remove(redirectUri, 'redirectUri')">
                        {{redirectUri}}
                        <button matChipRemove>
                            <mat-icon>cancel</mat-icon>
                        </button>
                    </mat-chip>
                    <input placeholder="New redirect uri..." [matChipInputFor]="redirectUrisList"
                        [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="true"
                        (matChipInputTokenEnd)="add($event, 'redirectUri')">
                </mat-chip-list>
            </mat-form-field>

The problem is that my formControl is always wrong, but when I assign formControlName to input instead of mat-chip-list, it's always without wrongs even when there are no items in the list.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source