Angular form disable submit button if field is empty

Sounds so simple, but I've tried quite a few things and none of them work.

I am using Angular 4 and my form is template driven:

<form #form="ngForm" novalidate>
    <label for="insz">{{ 'SEARCH_PAGE.searchInszNumber' | translate }}</label>
    <input type="text" name="insz" [placeholder]="'SEARCH_PAGE.searchInszNumber' | translate" #input required>
    <button (click)="onSearch(input.value)" ><span>{{'SEARCH_PAGE.search' | translate }}</span></button>
</form>

      

I want to disable a button when the input field is (one and only) empty.

+3


source to share


2 answers


You are missing ngModel

on your input as your input field is actually a form control:

<input type="text" name="insz" ngModel
    [placeholder]="'SEARCH_PAGE.searchInszNumber' | translate" #input required>

      



and then you need to disable the button if the form is invalid:

<button [disabled]="!form.valid" (click)="onSearch(input.value)" >Submit</button>

      

+2


source


You can take a look at reactive forms . I didn't know them until a week ago, but they are so powerful!



This means that all you have to do is add Validator

( Validators.required

in your case) and add the disabled condition to your button. And that, you are in tune.

0


source







All Articles