When it comes to angular form validation, passing null when the field is valid may seem a bit confusing at first. However, that's how it works. For more information, you can refer to this link and this one.
Here is a Plunker link that I have forked from your work. I have made a slight change where null will be returned for valid fields, and ValidationErrors for invalid ones. Additionally, I have included the errors object of the field in the HTML for clearer validation status.
https://embed.plnkr.co/t0gniM/
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
Please open developer console to check the exception <br>
Type anything and click anywhere other than the textbox<br><br>
<form [formGroup]="formObj">
<input type="text" id="username" formControlName="username" placeholder="Username" />
{{formObj.controls['username'].errors|json}}
</form>
</div>
`,
})
export class App {
name:string;
shouldBeUnique(control:AbstractControl):Promise<ValidationErrors|null>{
return new Promise((resolve, reject) => {
setTimeout(() => {
if (control.value === 'vikash') {
console.log('---matched--');
resolve(null);
}else{
resolve({ shouldBeUnique: true });
}
}, 1000);
});
}
formObj = new FormGroup({
username: new FormControl('', [
Validators.required
], [
this.shouldBeUnique
])
});
constructor() {
this.name = `Angular! v${VERSION.full}`
}
}
@NgModule({
imports: [ BrowserModule,FormsModule,ReactiveFormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
I hope this explanation helps clarify things for you.