Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 479
TanvirArjel Avatar asked Jan 17 '18 08:01

TanvirArjel


People also ask

What is the use of [( ngModel )] in 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.

Which of the following lines should be imported into app module TS to use template driven forms?

To use template-driven forms, Angular requires the FormsModule to be imported into your AppModule (app. module. ts).


1 Answers

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

like image 105
Rahul Singh Avatar answered Sep 28 '22 05:09

Rahul Singh