I already code service for Async Validator but I want to code generic Directive for this. Here is my code;
import { Directive } from '@angular/core';
import {AbstractControl, AsyncValidator, NG_ASYNC_VALIDATORS, ValidationErrors} from "@angular/forms";
import {Observable} from "rxjs";
import {IUser} from "app/core/user/user.model";
import {UserService} from "app/core/user/user.service";
@Directive({
"selector": '[uniqueUsername][ngModel],[uniqueUsername][FormControl]',
providers: [
{provide: NG_ASYNC_VALIDATORS, useExisting: UniqueUsernameDirective, multi: true}
]
})
export class UniqueUsernameDirective implements AsyncValidator{
constructor(private userService: UserService) { }
validate(control: AbstractControl, currentUser?: IUser): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>{
const promise = new Promise<any>((resolve, reject) => {
if (currentUser?.login !== control.value) {
this.userService.userExits(control.value).subscribe(user => {
if (user?.login !== '') {
resolve(null);
}
},
response => {
resolve({'loginAlreadyExits': true});
});
}
});
return promise;
}
}
Here is what I am getting error;
/Users/aygunozdemir/IdeaProjects/inuka-ng/src/main/webapp/app/shared/validators/unique-username.directive.ts 10:49 error 'UniqueUsernameDirective' was used before it was defined @typescript-eslint/no-use-before-define
✖ 1 problem (1 error, 0 warnings)
Here is my document ; https://weblog.west-wind.com/posts/2019/Nov/18/Creating-Angular-Synchronous-and-Asynchronous-Validators-for-Template-Validation
Also how can I add input to inside directive, basically
<input type="text" class="form-control" id="login" name="login" formControlName="login" uniqueUsername[???? shal I put here 'currentUser']>
To use your uniqueUsername validation directive within your form input control apply it as follows:
<input type="text" class="form-control" id="login" name="login"
formControlName="login" uniqueUsername={{currentUser}}>
Where currentUser is a variable within your component that you wish to validate.
Also remember to declare your validation directive within your application module:
@NgModule({
declarations: [
. . .
UniqueUsernameDirective
],
...