0

私はIonic 2を使用しており、ホームページ(親コンポーネント)があり、ホームページ内にタブレイアウトがあり、Ionic 2では各タブが個別のコンポーネント(子コンポーネント)であるユースケースがあります。

そのため、1 つのタブにユーザーのリストを表示しています。ホームページには、ユーザーが他のユーザーを検索できる検索バーもあります。したがって、ユーザーが検索バーに入力すると、ホームページ(親コンポーネント)で定義された関数がトリガーされますが、この関数がトリガーされると、フィルターするユーザータブ(子コンポーネント)でイベントを発生させる必要がありますユーザーリストとユーザータブの表示。これを解決するには助けが必要です。以下は私のコードです

<ion-content>
   <ion-tabs>
        //UsersTab comopnent class needs to know when getUsers function is triggered from home page
       <ion-tab tabTitle="List of Users" [root]="UsersTab"></<ion-tab>
       <ion-tab tabTitle="Tab 2" [root]="Tab2"></<ion-tab>
   </ion-tabs>
</ion-content>
<ion-footer>
    <ion-toolbar>
       <ion-title>
           // getUsers function will be defined is home page component class
           <ion-searchbar (ionInput)="getUsers($event)"></ion-searchbar>
       </ion-title>
    </ion-toolbar>
</ion-footer>

私の質問が理解しやすいことを願っています。

4

1 に答える 1

1

この plunkerでわかるように、共有サービスを使用することでそれを実現できます。

このサービスは、アイテムのリストを保存し、それをフィルタリングする役割を果たします。

import { Injectable } from "@angular/core";

@Injectable()
export class SharedService { 

  private userList: Array<string>;

  constructor(){
    this.initialiceUsers();
  }

  public initialiceUsers(){
    this.userList = [
      'Asdf Asdf',
      'Zxc Zxc',
      'Qwer Qwer',
      'Uiop Uiop'
    ];
  }

  public setUsers(users: Array<string>): void{
    this.userList = users;
  }

  public getUsers(): Array<string> {
    return this.userList;
  }

  public filterUsers(ev) {
    // Reset items back to all of the items
    this.initialiceUsers();

    // set val to the value of the searchbar
    let val = ev.target.value;

    // if the value is an empty string don't filter the items
    if (val && val.trim() != '') {
      this.userList = this.userList.filter((item) => {
        return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
  } 
}

親コンポーネントと子コンポーネントの両方が、そのサービスを使用して検索バーの値を送信し (項目をフィルタリングするため)、ビューに表示する項目のリストを取得します。

于 2016-08-23T10:09:11.107 に答える