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?
The ngModel directive declared in the FormsModule lets you bind controls in your template-driven form to properties in your data model.
To use template-driven forms, Angular requires the FormsModule to be imported into your AppModule (app. module. ts).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With