How to bind custom error to a Template Driven form

2020-04-08 13:19发布

In case of Model Driven form or Reactive form we can bind the custom error to an input field as follows:

In Component:

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

My question is how can we do the same thing in case of Template Driven form?

1条回答
▲ chillily
2楼-- · 2020-04-08 13:38

You can make use of View Child in this scenario get an instance of the ngForm in the component backend model and then add all the validations and errors to it

Something like this

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 });

For More detailed info check my ts file which i created for such a scenario link

查看更多
登录 后发表回答