如何将自定义错误绑定到angular5中的模板驱动表单输入字段

How to bind custom error to a Template Driven form input field in angular5

在模型驱动表单或反应表单的情况下,我们可以将自定义错误绑定到输入字段,如下所示:

在组件中:

sampleForm.controls["formControlName"].setErrors({ 'incorrect': true });

我的问题是在模板驱动形式的情况下我们如何做同样的事情?

您可以在这种情况下使用 View Child 在组件后端模型中获取 ngForm 的实例,然后向其添加所有验证和错误

像这样

f: NgForm; // f is nothing but the template reference of the Template Driven Form
@ViewChild('f') currentForm: NgForm;
currentForm.form.controls["formControlName"].setErrors({ 'incorrect': true });

有关更多详细信息,请查看我为此类场景创建的 ts 文件 link