【问题标题】:disable button typescript with condition禁用带有条件的按钮打字稿
【发布时间】:2018-06-04 04:52:11
【问题描述】:

我想禁用带有条件的按钮,例如我已经用关键的日期制作了一个数据。我想禁用用于创建与我已经将其推送到 Firebase 的数据具有相同日期的新数据的按钮。我在 html 上的代码是这样的:

<button ion-button full (click)="submitLaporan()" color='secondary' [disabled]="isEnabled()">Buat laporan harian</button>

这是打字稿上的代码:

isEnabled()
  {
    this.db.list('/laporan/'+this.id).subscribe(laporan =>{
      for(var i =0,j = 0;i<laporan.length;i++)
      {
        console.log("masuk laporan",laporan);
        if(laporan[i].mydate == this.tanggal)  
            return false;
        else
        {
          return true;
        }
      }
    })
  }

在函数isEnabled() 上我想查询我的firebase 中的所有数据,然后将其与日期进行比较,如果firebase 上的日期和ionic 上的日期具有相同的值,它应该返回false 并且按钮被禁用。但这根本不起作用。

我没有与 ionic 日期相同但按钮保持禁用的数据。它应该被启用。

【问题讨论】:

    标签: typescript firebase ionic-framework firebase-realtime-database angularfire2


    【解决方案1】:

    for 循环中的return value 存在问题。鉴于您的代码编写方式,将仅检查第一个元素,如果它等于this.tanggal,它将返回 false,否则将返回 true

    您想要实现的是返回false,如果对于所有元素,都没有包含给定日期的元素。如果找到给定日期的出现,它将返回true

    this.db.list('/laporan/'+this.id).subscribe(laporan =>{
        let myVal = false;
        for(var i =0,j = 0;i<laporan.length;i++)
              {
                console.log("masuk laporan",laporan);
                if(laporan[i].mydate === this.tanggal)  
                    myVal = true;
    
              }
        return myVal
     })
    

    【讨论】:

    • laporan[i].mydate 是字符串,this.tanggal 是iso字符串,但我已经剪断了字符串,我认为我比较日期的方式没有错,因为我可以显示firebase 和 ionic 中具有相同日期的数据
    • 字符串是否相等?
    • 是的,字符串相等,我从日期的子字符串中推送 mydate 值
    【解决方案2】:

    html

    <button ... [disabled]="isEnabled() | async">Buat laporan harian</button>
    

    打字稿

    isEnabled() {
        return this.db.list('/laporan/'+this.id).switchMap(laporan =>{
          for(let i=0, x=laporan.length; i<x ;i++) {
            console.log("masuk laporan",laporan);
    
            if(laporan[i].mydate == this.tanggal) {
              return Observable.of(false);
            }
          }
          return Observable.of(true);
        });
    }
    

    您可能需要添加以下 3 行:

    import { Observable } from 'rxjs/Observable';
    import { of }         from 'rxjs/observable/of';
    import { switchMap }  from 'rxjs/operators';
    

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 2018-07-18
      • 2018-05-26
      • 2021-06-24
      相关资源
      最近更新 更多