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

Tan*_*jel 4 typescript angular angular5

对于“模型驱动”表单或“反应式”表单,我们可以将自定义错误绑定到输入字段,如下所示:

在组件中:

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

我的问题是,在“模板驱动”表单的情况下,我们该怎么做?

Rah*_*ngh 5

您可以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 });
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请检查我为这种情况创建的ts文件 link