如何在 blur/focus in/change 上触发验证消息?
我试过的:
import { FormGroup, Validators, FormBuilder, FormControlName, FormControl } from '@angular/forms';
// Component - Class implementation:
addressForm: FormGroup;
consructor(private fb: FormBuilder) { }
ngOnInit() {
this.addressForm = this.fb.group({
zip: ['', {
validators: [Validators.required, Validators.minLength(4)],
updateOn: 'change' //blur
}]
});
}
但它不起作用..
最佳答案
我也遇到了这个问题,我像往常一样用指令和服务解决了它。该指令附加到输入元素,服务协调应该触发验证的事件。
这是指令:
@Directive({
selector: 'input, textarea, select'
})
export class TriggerValidationDirective {
constructor(private svc: TriggerValidationService, private el: ElementRef) {
}
@HostListener('blur', ['$event'])
@HostListener('selectionChange', ['$event'])
@HostListener('change', ['$event'])
onTriggerValidation(e) {
this.svc.triggerValidation(this.el);
}
}
这是服务@Injectable({ providedIn: 'root' })
export class TriggerValidationService {
private triggerValidationSubject = new Subject<ElementRef | null>();
triggerValidation$ = this.triggerValidationSubject.asObservable();
triggerValidation(el?: ElementRef<any>) {
this.triggerValidationSubject.next(el);
}
}
这是我在包含 react 形式的组件中使用它的方法:@Component({
// ... selector, etc.
providers: [ { provide: TriggerValidationService, useClass: TriggerValidationService } ]
})
export class TheComponent implements OnInit, OnDestroy {
constructor(private triggerValidationService: TriggerValidationService) {}
ngOnInit() {
this.sub = this.triggerValidationService.triggerValidation$.subscribe(_ => {
// trigger validation, e.g. this->formGroup.updateValueAndValidity();
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
简要回顾一下这是如何工作的:该指令附加到所有相关的输入元素(文本输入、文本区域、日期选择器、选择等)并监听我们想要用来触发验证的适当事件。该指令然后通知在 observable 上发出的服务。托管表单的组件订阅该 observable 并在它发出时执行有效性检查。重要提示:请注意,该服务必须由托管表单的组件提供(请注意组件装饰器中的
providers
部分),以便不同的表单不会触发彼此的验证。
关于Angular 6 Reactive forms - 触发焦点/模糊验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51554069/