button disabled not working properly angular

2k views Asked by At

Here is my scenario, where I have a date picker and a save button.

I am disabling the save button when the date is not available. Actually my code is working in general scenario

Here is my current code:

disableDate() {
for (let index = 0; index < this.dataSource.data.length; index++) {
  if (this.dataSource.data[index].detail[0].dob != '' && this.dataSource.data[index].detail[0].dob != null
    && this.dataSource.data[index].detail[0].doe != '' && this.dataSource.data[index].detail[0].doe != null
    && this.dataSource.data[index].detail[0].dom != '' && this.dataSource.data[index].detail[0].dom != null
  ) {
    if (this.formatDate(this.dataSource.data[index].detail[0].dob) > this.formatDate(this.dataSource.data[index].detail[0].doe)) {
      return true;
    }
  }
}
   return false;
}

Here is my HTML code for disabling the button

<button mat-raised-button class="mx-1" color="primary" (click)="saveLplv()"
  [disabled]="disableDate()">Save</button>

What I am doing wrong here; why disable button not working properly?

2

There are 2 answers

1
Wasim On

First :
Return type of disableDate should be bool.

Second

I would recommend you make a variable like disableBtn initially assign it false value

 disableBtn: boolean = false

Then in the method where you are checking condition , change status of button to true/false according your case

2
Ujjwal Choudhary On

Instead of false return null. An attribute like disabled, readonly is removed from HTML element only if it's value is null.