abidinberkay
abidinberkay

Reputation: 2025

How to disable button if there is no input entered including space char in Angular

I have a simple input field and 1 button for save it. If the input field is empty, then button becomes disabled. But with my code, space character is acting like normal character so user can enter value by just putting space. How can i check at least 1 char exist on input field?

the code:

<mat-form-field fxFlex="50">
            <input matInput name="postalAddress"
                   [(ngModel)]="employee.postalAddress" placeholder="Postal Address"
                   required>
</mat-form-field>

 <button type="button" id="save" class="button-style" (click)="onSaveOffice()"
                [disabled]="!employee.postalAddress" > Save
 </button>

Note: I am using typescript at back so do i need to do any logic at typescript code ?

Upvotes: 0

Views: 1205

Answers (1)

Amir Arbabian
Amir Arbabian

Reputation: 3699

You can use trim() method on string before checking emptiness, so it will remove all the spaces:

<mat-form-field fxFlex="50">
            <input matInput name="postalAddress"
                   [(ngModel)]="employee.postalAddress" placeholder="Postal Address"
                   required>
</mat-form-field>

 <button type="button" id="save" class="button-style" (click)="onSaveOffice()"
                [disabled]="!employee.postalAddress?.trim()" > Save
 </button>

Hope that helps.

Upvotes: 3

Related Questions