I'm doing a web application in Angular 8.3.4. I have a form using Reactive Forms and I want to add Async Validation to make sure that the name entered is unique. I have read a lot of examples out there, but for some reason is not working for me.
Service
export class BrandService {
brands: Observable<BrandId[]>;
}
Component
export class CreateNewComponent {
form: FormGroup;
constructor(
private formBuilder: FormBuilder,
private brandService: BrandService
) {
// Creates a form group
this.form = this.formBuilder.group({
name: ['', Validators.compose([
Validators.required,
Validators.minLength(6),
CustomValidator.unique(this.brandService.brands)
])]
});
}
}
Custom validator
export class CustomValidator {
static unique(brands: Observable<BrandId[]>) {
return (control: AbstractControl) => {
const name = control.value.toLowerCase();
return brands.pipe(
map(items => items.filter(b => b.name.toLowerCase() === name)),
map(items => items.length ? {unique: false} : null)
);
};
}
}
I'm passing the Observable of the service from the component to the CustomValidator. Right now, the control has: status: "INVALID"
By the way, what should I explicitly return in my unique method?
My goal is to know if the name already exists in the array of the Observable to return a control error.