Angular, Disable submit button using [disabled] to check form validity

Wira Xie picture Wira Xie · Jan 31, 2018 · Viewed 53k times · Source

I'm trying to disable a submit button using [disable]=form.controls[...].invalid condition checking. The submit button should be disabled if there is an input fields is empty or invalid. But looks like i'm doing it wrong. The button is disabled when i fill some fields and left some fields empty, except for the first input field . When i filled the first input field, the button become enabled (while the other input fields are still empty or invalid).

I'm using Angular typescript and myDatePicker package from this link. Can anyone help me please?

Answer

moohkooh picture moohkooh · Jan 31, 2018

You can enable/disable the button by checking the validity of your form:

<button type="submit" [disabled]="!disableBtn">Click</button>

Inside your component:

let disableBtn = false;
this. form01.valueChanges 
            .subscribe((changedObj: any) => {
                 this.disableBtn = this. form01.valid;
            });

Or via HTML:

<button type="submit" [disabled]="!form01.valid" (click)="functionForm01()">Click</button>