Dev
Dev

Reputation: 828

How to manually set an Angular template driven form as invalid in angular9

I want to manually set the EmployeeForm as Invalid from the .ts file. Here EmployeeForm is a Template driven form.

I have tried to do the following but it didn't work.

this.EmployeeForm.setErrors({ 'invalid': true }); 

error message says:

Property 'setErrors' does not exist on type 'NgForm'. Did you mean 'getError'?

The same code works when I use it with other forms which are Reactive forms

Upvotes: 3

Views: 4859

Answers (2)

Ahmed Khairy
Ahmed Khairy

Reputation: 61

You can add the template reference to your control input. Then, you can access the form control and add the errors which you want.

Ex: <input type="text" class="form-control" id="name" required [(ngModel)]="model.name" name="name" #name="ngModel">

Reference: Angular Docs.

Upvotes: 0

Dev
Dev

Reputation: 828

Finally this worked

this.EmployeeForm.form.setErrors({ 'invalid': true });

Upvotes: 2

Related Questions