Raj
Raj

Reputation: 1120

How to validate angular form, having material form field?

I have a form which uses Angular material form fields. I want to disable the submit button, till all the form controls are filled with appropriate value. (code is given as links in the description)

When i am using material components in template(code), and define controls(code) in components, this is the output. ok

Problem

When I implement formsBuilder or forms group in template and in component, the material components won't display properly.

enter image description here

Question

How can I disable/enable submit button only if all the material forms fiields are evaluated to true

Thanks in advance.

Upvotes: 2

Views: 4041

Answers (1)

user184994
user184994

Reputation: 18271

You should start by making your fields part of a FormGroup, like so:

group = new FormGroup({
  cNameControl: new FormControl('', [Validators.required, Validators.minLength(3)]),
  cDescControl: new FormControl('', [Validators.required])
})

You can now point the form tag at your form group:

<form class="example-container" #addCategoryForm="ngForm"  [formGroup]="group">

And point your controls at the FormControls:

<input matInput placeholder="name" formControlName="cNameControl">

Note that there is no [ surrounding formControlName, because we're using a string literal

Finally, change your disabled tag, so that it's disabled if the form is not valid:

[disabled]="!addCategoryForm.valid"

With all that combined, it should work.

Here is a StackBlitz demo

Upvotes: 3

Related Questions