Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is *ngIf not working when a variable is settled to 0?

I have 3 input fields with [(ngModel)] to 3 variables.

Then I have a hidden button that only appears when all 3 variables have a value, using *ngIf. Check out the code:

<mat-form-field>
    <input matInput [matDatepicker]="picker" placeholder="Fecha" [(ngModel)]="matchDay">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<mat-form-field>
        <input matInput placeholder="Hora" type="number" min='00' max='23' [(ngModel)]="matchHours">
</mat-form-field>
<mat-form-field>
        <input matInput placeholder="Minutos" type="number" min='00' max='59' [(ngModel)]="matchMinutes">
</mat-form-field>
<div class="button-row" *ngIf="matchHours && matchDay && matchMinutes">
        <button mat-raised-button color="accent" (click)="setMatchDate()">Set Date</button>
</div>

The problem is that if "matchHours" or "matchMinutes" have 0 or 00 value, the "Set Date" button does not appear as if the *ngIf condition was not met.

Any ideas what might be happening here?

Here is the ts code:

export class CreateMatchComponent implements OnInit {

  matchDay: Date;
  matchHours: number;
  matchMinutes: number;

setMatchDate() {
    let parsedDate = this.matchDay.toISOString().split('T');
    this.match.matchDate = this.createFormattedMatchDate(parsedDate[0], this.matchHours, this.matchMinutes);
    console.log(this.match.matchDate);
  }

  createFormattedMatchDate(parsedDate: string, hour: number, minute: number) {
    minute = pad(minute);
    hour = pad(hour);
    function pad(n) {
      return (n < 10 && n >= 0) ? ("0" + n) : n;
    }
    let formattedDate = parsedDate + "T" + (hour + 3) + ":" + minute + ":00";
    return formattedDate; 
  } 
}
like image 404
Matias Diez Avatar asked Oct 27 '25 06:10

Matias Diez


1 Answers

As 0 is considered falsy in javascript, so *ngIf gets it as false and your button does not appear. You can use an string type value '0' so it won't be considered as false.

For more information about falsy see : https://developer.mozilla.org/en-US/docs/Glossary/Falsy

like image 106
Rohan Sampat Avatar answered Oct 29 '25 18:10

Rohan Sampat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!