简体   繁体   中英

how to pass data (or raise a event) from parent component to child component without using @input decorator in Ionic2

I am working with Ionic 2 and have a use case where there is a home page (parent component) and inside home page there is a tab layout and in Ionic 2 each tab is a separate component (child components).

so in one tab, I am showing list of users and in home page there is also a search bar through which user can search other users. So Now when user types in search bar, a function is getting triggered which is defined in Home page (parent component) but when this function get triggered I need to raise a event in user tab (child component) in which I am going to filter the user list and display in user tab. Need help in solving this. The following is my code

<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>

I hope my question is easy to understand.

You can achieve that by using a shared service like you can see in this plunker .

The service will be responsible for storing the list of items and filter it:

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);
      })
    }
  } 
}

And both the parent component and the child component, will use that service to send the value of the search bar (to filter the items) and to obtain the list of items to show in the view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM