从 HostListener 事件中将表单字段设置为无效

Set form field as invalid from HostListener event

我正在使用 angular 4 并且对它很陌生。我可能会使用模板驱动的表单。我有一个表单字段,上面有一些模式匹配。所以我注册了一些事件,比如

@HostListener('blur', ['$event'])
    onBlur(event) {
        // this.validateFormControl.markAsTouched();
        console.log(event);
        console.log(this.elementRef)
console.log(this.elementRef.nativeElement)

我想检查它里面的表单元素的状态是什么,比如它是有效还是无效,并做一些额外的检查,并根据它内部的某些条件将表单元素设置为无效。如何在此函数内部将表单元素设置为无效。

Template Driven Forms are very limited compared to Reactive Forms 并且我强烈建议使用后者,因为它背后有强大的 API。

但如果您真的需要使用 Template Driven Forms 进行破解以添加一些自定义验证,您可以尝试使用表单元素的 setCustomValiditycheckValidity 方法。

我不建议为 Template Driven Forms, because this is not the way they were originally designed, instead, use Reactive Forms and read this guide 创建任何程序验证。