網站搜尋

typescript - 如何在 ionic3 中當選擇/取消選擇「全選」選項時勾選/取消勾選 ion-select 中的所有選項


這是我的程式碼,我想使用它在當「全選」ion-option 被選取/取消選取時,檢查/取消檢查下拉選單中的所有選項。

items:any =[
      {id:1, value:"Apple"}
      {id:2, value:"Banana"}
      {id:3, value:"Stawberry"}
      {id:4, value:"PineApple"}
      {id:5, value:"Grapes"}
      ];
    selectedItems:any;
    selectAll:boolean;
    
    /**
     * This select all the items in the ion-select  popup
     **/
    selectAllItems() {
      if(!selectAll) {
        this.items.filter(Obj => {
          this.selectedItems.push(Obj.id);
        });
        this.selectedItems.push(0);
        this.selectAll = true;
      } else {
        this.selectedItems = this.items[0].id;
      }
    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ion-item>
        <ion-label>Multiselect</ion-label>
        <ion-select [(ngModel)]="selectedItems">
          <ion-option (ionSelect)="selectAllItems()" [value]="0">
            Select All
          </ion-option>
          <ion-option *ngFor="let item of items" [value]="item.id">
            {{item.value}}
          </ion-option>
        </ion-select>
      </ion-item>

當我使用 (ionSelect) 時,模型會發生變化,但所有選項都沒有被選中,並且當我取消選中時,ionSelect 事件沒有被觸發。這是在 ionic-3 中完成的。有人能幫我嗎。提前感謝

答案#1

只需在所選項目中插入所有項目的ID

constructor(private ngZone: NgZone){
}

selectAllItems() {
    if (!selectAll) {
      this.ngZone.run(() => {
        for (let item of items) {
          this.selectedItems.push(item.id)
          this.selectAll = true;
        }
      })
    } else {
      this.selectedItems = [];
      this.selectAll = false;
    }

並且在選擇中設置 selectAll 的值

<ion-option (ionSelect)="selectAllItems()" [value]="selectAll">
            Select All
          </ion-option>