要根据验证器正确查找和添加类到Angular元素,您可以使用Angular的自定义指令和验证器函数。以下是一个解决方案的示例代码:
首先,创建一个自定义指令,将验证器函数作为参数传递给该指令:
import { Directive, ElementRef, Input, OnChanges, SimpleChanges } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl, ValidatorFn } from '@angular/forms';
@Directive({
selector: '[appCustomValidator]',
providers: [{
provide: NG_VALIDATORS,
useExisting: CustomValidatorDirective,
multi: true
}]
})
export class CustomValidatorDirective implements Validator, OnChanges {
@Input('appCustomValidator') appCustomValidator: ValidatorFn;
constructor(private el: ElementRef) {}
ngOnChanges(changes: SimpleChanges): void {
if ('appCustomValidator' in changes) {
const control = this.el.nativeElement;
control.classList.remove('valid', 'invalid');
control.classList.add('pending');
}
}
validate(control: AbstractControl): { [key: string]: any } | null {
const validationResult = this.appCustomValidator(control);
const controlElement = this.el.nativeElement;
controlElement.classList.remove('pending');
if (validationResult === null) {
controlElement.classList.add('valid');
controlElement.classList.remove('invalid');
} else {
controlElement.classList.add('invalid');
controlElement.classList.remove('valid');
}
return validationResult;
}
}
然后,在使用该验证器的组件中,将验证器函数传递给自定义指令:
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
template: `
`
})
export class AppComponent {
myValue: string;
myValidator(control: FormControl): { [key: string]: any } | null {
if (control.value && control.value.length > 5) {
return null; // valid
} else {
return { 'customError': true }; // invalid
}
}
}
在上面的示例中,当用户输入的值不符合验证器函数的条件时,将添加名为"invalid"的类到输入框元素。当用户输入的值满足验证器函数的条件时,将添加名为"valid"的类到输入框元素。此外,还添加了一个名为"pending"的类,以在验证过程中显示加载状态。
请注意,示例中使用的是Angular的响应式表单(Reactive Forms)。如果您使用的是模板驱动形式(Template-driven Forms),则需要相应地更改代码。