【问题标题】:How to add checked and unchecked checkboxes data to Firebase如何将选中和未选中的复选框数据添加到 Firebase
【发布时间】:2019-08-21 12:12:06
【问题描述】:

我的 Ionic 3 应用中有一个对象数组作为起始数据:

public interesses = [
    { name: 'Viagens', checked: false  },
    { name: 'Animais', checked: false  },
    { name: 'Teatro', checked: false  },
    { name: 'Outros', checked: false  }
  ];

我正在尝试从此数组创建多个复选框,并将所有数据添加到 Firebase 中,包括此列表中已选中和未选中的项目。

目前,我的 .ts 代码是:

interessesG :any = [];
profileForm: FormGroup;

  constructor(public navCtrl: NavController, 
    public navParams: NavParams, 
    private afAuth: AngularFireAuth, 
    public db: AngularFireDatabase,
    public fb: FormBuilder) {

      this.profileForm = fb.group({
        interesses: new FormArray([])
      });
  }

checado(data, i, isChecked: boolean) {
    this.interessesG = <FormArray>this.profileForm.controls.interesses;

    if (isChecked) {
      this.interessesG.push(new FormControl({name: data.name, checked: true}));
      console.log(this.interessesG.value);
    } else {
      let index = this.interessesG.controls.findIndex(x => x.value == data)
      this.interessesG.removeAt(index);
      console.log(this.interessesG.value);
    }
  }

saveProfile(){
    this.db.object('users/' + this.userId).update({     
      interesses:   this.interessesG.value        
    }).then(() => {
      console.log("Success!");
      }, error => {
        console.error(error);
      }
    );
  }

还有我的 .html 文件:

<div formArrayName="interesses">
  <ion-item class="int-list" no-lines *ngFor="let int of interesses; let i = index">
    <ion-label>{{int.name}}</ion-label>
    <ion-checkbox slot="end" (ionChange)="checado(int, i, $event.checked)"></ion-checkbox>
  </ion-item>
</div>

使用此代码,我只得到选中的项目(显示在控制台上):

0: {name: "Animais", checked: true}

但我需要得到这样的东西:

0: { name: 'Viagens', checked: false  },
1: { name: 'Animais', checked: true  },
2: { name: 'Teatro', checked: false  },
3: { name: 'Outros', checked: false  }

我该怎么做?

【问题讨论】:

    标签: javascript firebase-realtime-database ionic3 angularfire2


    【解决方案1】:

    您可以直接更改现有数组以获得数组中的所有对象值。

    checado(data, i, isChecked: boolean) {
        let newObj = data;
        newObj.checked = isChecked;
        this.interesses[i] = newObj;
        console.log(this.interesses);
    }
    

    如果您只想要对象,请使用以下内容。

    console.log(...this.interesses);
    

    我用您的代码创建了一个 stackblitz 示例。 https://stackblitz.com/edit/ionic-58mfcp

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-19
      • 2013-11-08
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多