Как я могу вызвать функцию динамически через мой цикл? - PullRequest
1 голос
/ 16 мая 2019

Я не знаю, как сформулировать свой вопрос, потому что я довольно новичок в разработке ионных и гибридных приложений в целом, но я буду стараться изо всех сил. Я работаю над приложением и хочу открыть поле ion-select, нажав на другую кнопку.

Это несколько работает, но не удаляет нужную запись, если нажатая запись не первая.

Мой HTML-код выглядит так:

account.page.html

<div class="account-drop-wrapper" *ngFor="let item of myDrops">
  <div class="account-item">
    <div class="account-content" [routerLink]="['/drop', item.id]">
      <div class="text-content">
        {{ item.description }}
      </div>
      <div class="drop-score">
        <ion-progress-bar color="primary" value="0.5"></ion-progress-bar>
        <p>{{ item.score }}</p>
      </div>
    </div>
      <ion-item class="more-button">
        <ion-icon name="more" class="edit-icon" (click)="openSelect()"></ion-icon>
        <ion-select class="select-field" interface="action-sheet" (ionChange)="showMore(item, $event)" #showSelect>
          <ion-select-option value="delete">Löschen</ion-select-option>
          <ion-select-option value="edit">Bearbeiten</ion-select-option>
        </ion-select>
      </ion-item>
  </div>
</div>

и это пока мой TypeScript:

account.page.ts

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { DropService } from '../../services/drop.service';
    import { Events, IonSelect, NavController } from '@ionic/angular';
    import { AlertController } from '@ionic/angular';


    @Component({
      selector: 'app-account',
      templateUrl: './account.page.html',
      styleUrls: ['./account.page.scss'],
    })
    export class AccountPage implements OnInit {

      allDrops: Drop[];
      myDrops: Drop[];

      @ViewChild('showSelect') selectRef: IonSelect;

      openSelect() {
        this.selectRef.open();
      }

      constructor(private dropService: DropService, 
         public navCtrl: NavController, 
         public events: Events, 
         public alertController: AlertController) { }

      ngOnInit() {
        this.dropService.getDrops().subscribe(res => {
              this.allDrops = res;
          });

        this.dropService.getMyDrops().subscribe(res => {
          this.myDrops = res;
        });
      }

      showMore(item, event) {
        if (event.detail.value === 'delete') {
          this.confirmDelete(item);
        }
      }

      async confirmDelete(item) {
        const alert = await this.alertController.create({
          header: 'Confirm',
          message: 'delete?',
          buttons: [
            {
              text: 'cancel',
              role: 'cancel',
              cssClass: 'secondary'
            }, {
              text: 'delete',
              handler: () => {
                this.dropService.removeDrop(item.id);
              }
            }
          ]
        });
        await alert.present();
      }
    }

Я думаю, мне нужно сделать каждый ion-select уникальным, примерно так:

    <ion-select (ionChange)="showMore(item, $event)" #showSelect{{item.id}}>

Но, к сожалению, я не знаю правильный синтаксис для достижения этого ... Кто-нибудь может мне помочь или исправить меня, если я ошибаюсь в своих предположениях?

1 Ответ

1 голос
/ 16 мая 2019

Насколько я понимаю, у вас есть несколько ion-select компонентов на вашей странице, и вам нужно получить ссылку на определенный ion-select, чтобы открыть его из вашего кода.

Я предполагаюion-select компоненты находятся внутри *ngFor

<div *ngFor="let item of allItems" class="some-class">

  <!-- Some other content... -->

  <!-- Send the item to the openSelect() method -->
  <ion-icon name="more" class="edit-icon" (click)="openSelect(item)"></ion-icon>

  <ion-select (ionChange)="showMore(item, $event)" #showSelect>
    <!-- options... -->
  </ion-select>

</div>

Если это правильно, то вы можете использовать ViewChildren в своем компоненте, чтобы получить все экземпляры ionSelect компонент, а затем найдите правильный на основе его индекса, как это:

import { Component, OnInit, ViewChildren, QueryList } from '@angular/core';
import { DropService } from '../../services/drop.service';
import { Events, IonSelect, NavController } from '@ionic/angular';
import { AlertController } from '@ionic/angular';

@Component({
  selector: 'app-account',
  templateUrl: './account.page.html',
  styleUrls: ['./account.page.scss'],
})
export class AccountPage implements OnInit {

  // Now it's a QueryList of IonSelect instances
  @ViewChildren('showSelect') selectRefs: QueryList<IonSelect>;

  // This is the list of all the items that you use in the ngFor
  public allItems: Array<any>;

  openSelect(item: any) {

    // First find the index of the item in the allItems array
    const targetIndex = allItems.findIndex(someItem => someItem.id === item.id);

    if(targetIndex > -1) {

      // then get the IonSelect from the QueryList using the same index
      const targetIonSelect = this.selectRefs.toArray()[targetIndex];

      if(targetIonSelect) {

        // Now you can open that IonSelect instance
        targetIonSelect.open();

      }

    }

  }

  // ...

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...