为什么 *ngIf 在变量设置为 0 时不起作用?

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

我有 3 个输入字段 [(ngModel)] 到 3 个变量。

然后我有一个隐藏按钮,只有当所有 3 个变量都有值时才会出现,使用 *ngIf。查看代码:

<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>

问题是,如果 "matchHours" 或 "matchMinutes" 的值为 0 或 00,则 "Set Date" 按钮不会出现,就好像 *ngIf 条件不满足一样。

知道这里会发生什么吗?

这是ts代码:

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; 
  } 
}

因为 0 在 javascript 中被认为是假的,所以 *ngIf 将它作为假,你的按钮不会出现。您可以使用字符串类型值“0”,这样它就不会被视为 false。

有关 falsy 的更多信息,请参阅:https://developer.mozilla.org/en-US/docs/Glossary/Falsy