What is the process in Ionic 3 for invoking a method housed within a tab class?

I'm currently developing an Ionic app that features a "home" page with 3 tabs. My goal is to implement a search bar for these tabs by triggering a method inside the selected tab's class whenever the search term changes. Below is the structure of the home page:

<ion-header>
    <ion-navbar>
        <ion-title>{{title}}</ion-title>
        <ion-buttons end>
            <button [hidden]="title != 'Meu Cadastro'" ion-button color="dark" (click)="logout()">
                <ion-icon name="log-out"></ion-icon>
            </button>
        </ion-buttons>
    </ion-navbar>
    <ion-toolbar>
        <ion-searchbar [(ngModel)]="searchTerm" (ionInput)="setFilteredItems()"></ion-searchbar>
    </ion-toolbar>
</ion-header>
<ion-content >
    <ion-tabs #homeTabs>
        <ion-tab [root]="tabAten" tabTitle="Atendimentos" [rootParams]="innerInstance" tabIcon="construct"></ion-tab>
        <ion-tab [root]="tabEquip" tabTitle="Equipamentos" [rootParams]="innerInstance" tabIcon="build"></ion-tab>
        <ion-tab [root]="tabCad" tabTitle="Meu Cadastro" [rootParams]="innerInstance" tabIcon="contact"></ion-tab>
    </ion-tabs>

</ion-content>

import { Component, ViewChild } from '@angular/core';
import { NavController, AlertController, Tabs } from 'ionic-angular';
import { NativePageTransitions, NativeTransitionOptions } from "@ionic-native/native-page-transitions";

import { AtendimentosPage } from "../home/atendimentos/atendimentos";
import { EquipamentosPage } from "../home/equipamentos/equipamentos";
import { MeuCadastroPage } from "../home/meu_cadastro/meu_cadastro";

var instance: any;

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})

export class HomePage {

title: String;

@ViewChild('homeTabs') tabs: Tabs;

tabAten: any;
tabEquip: any;
tabCad: any;

searchTerm: string = '';

innerInstance: any;

constructor(public navCtrl: NavController
    , private alertCtrl: AlertController
    , private nativePageTransitions: NativePageTransitions) {
    instance = this;
    this.innerInstance = this;
    this.tabAten = AtendimentosPage;
    this.tabEquip = EquipamentosPage;
    this.tabCad = MeuCadastroPage;
}

setTitle(title: String) {
    this.title = title;
}

setFilteredItems() {

    switch (this.tabs._getSelectedTabIndex()) {
        //THIS is where I'm trying to call the method inside the 1st tab. The setFilteredItems() method is called whenever the search bar receives new text from the user.
        case 0: this.tabAten.filterItems(this.searchTerm);
            break;
        case 1: this.tabEquip.filterItems(this.searchTerm);
            break;
        default: break;
    }
}

Now let's take a look at the tab class:

<ion-content>
    <ion-list>
        <ion-item *ngFor="let a of atendimentos; let i = index" (click)="showDetails(i)">
            <div *ngIf="a.status != 'Concluído'">
               <!-- This is where data for each list item is displayed -->
            </div>
        </ion-item>
    </ion-list>
</ion-content>

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import { AtendimentoPage } from "../atendimentos/atendimento/atendimento";

import { Atendimento } from "../../../models/atendimento";

@Component({
    selector: 'page-home',
    templateUrl: 'atendimentos.html'
})

export class AtendimentosPage {

    options: NativeTransitionOptions;
    atendimentos: Array<Atendimento>;
    homeInstance: any;

    ionViewWillEnter() {
        this.homeInstance.setTitle("Atendimentos");
    }

    constructor(public navCtrl: NavController
        , private navParams: NavParams
        , private http: Http
        , private nativePageTransitions: NativePageTransitions) {
        this.homeInstance = navParams.data;
        this.atendimentos = new Array<Atendimento>();

        this.getAtendimentos(); // Method that does a web call to get array of objects, those will be filtered by the search bar.
    }

    public filterItems(searchTerm) {
        //THIS is the method that I want to call from the home page.
    }
}

When setting up the tabs on my home page, each one is assigned a corresponding class in the home page constructor. The template already recognizes these as tab roots. How can I access the specific class instance of the selected tab/page and utilize its methods?

Answer №1

After some investigation, I managed to identify a workaround for the issue I was facing. Although it's not directly related to Angular itself, it proved to be a reliable solution.

In my homepage HTML file, I made sure to pass a variable named "innerInstance" as rootParams when declaring my tabs. This variable holds an instance of the homepage object, allowing me to update the references to the tabs from mere class references to actual objects:

constructor(public navCtrl: NavController
        , private navParams: NavParams
        , private http: Http
        , private nativePageTransitions: NativePageTransitions) {

        // By accessing the homepage instance, I can redefine the reference to this particular tab
        this.homeInstance = navParams.data;

        this.atendimentos = new Array<Atendimento>();

        ...
    }

Although it may have seemed confusing initially, it has become clear to me now. If anyone encounters a similar issue, feel free to reach out for assistance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error message "The element 'router-outlet' is unrecognized during the execution of ng build --prod" appears

I encountered a specific error message when running ng build --prod, although the regular ng build command works without issue. Error: src/app/app.component.html:1:1 - error NG8001: 'router-outlet' is not recognized as an element: 1. If 'rou ...

How should a child component specify the type of component being passed in props?

Consider the following snippet from App.tsx : <Layout header={ <Header/> } </layout> Now, let's take a look at the Layout component : export default function Layout({header, body}: any) { return ( <div className="layou ...

Having trouble viewing the value of request headers in Firebase?

Here is my code snippet: var headers = new Headers(); headers.append("bunny", "test"); headers.append("rabbit", "jump"); fetch("blahurl.com/someservice", {headers:headers}) When it comes to handling the request on Firebase: export const listener = funct ...

Vue3 with Typescript may either display an error message or remain empty when handling props

I've been attempting to utilize the default Quasar card component in order to display data received from props. Unfortunately, I haven't had any success as my component remains empty and I keep encountering various errors with each attempt. Rece ...

Leveraging jQuery across multiple angular.json configurations and modules within an Angular application

Currently, I have a template that utilizes jQuery in various sections. In my angular.json file, I specify the following scripts: "scripts": [ "node_modules/jquery/dist/jquery.js", "src/assets/vendor/slimscroll/slimscroll.min.js", ] This setup works s ...

After executing "npm run dev" in Svelte and Vite, a common error message of "HTMLElement is not defined" might appear

Incorporating several web components into my Svelte project led to the appearance of an error message stating HTMLElement is not defined after running npm run dev (which actually translates to vite dev). The complete error message reads as follows: HTMLEl ...

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...

Exploring the Benefits of Utilizing the tslint.json Configuration File in an Angular 6 Project

https://i.stack.imgur.com/j5TCX.png Can you explain the importance of having two tslint.json files, one inside the src folder and one inside the project folder? What sets them apart from each other? ...

Error: Ionic 3 is unable to locate the specified pipe

I am unable to locate any issues with this problem. I have already imported it in app.module.ts and included it in the 'declaration' section. In app.module.ts import { NgModule, ErrorHandler } from '@angular/core'; import { BrowserMod ...

Pairing objects by utilizing a Universal Mapper

Classes Defined: abstract class ModelBase { id: string; } class Person extends ModelBase { favoriteDog: Dog | undefined; favoriteDogId: string | undefined; dogs: Dog[] } class Dog extends ModelBase { id: string; ownerId: string; name: strin ...

What is the best method for showcasing information within an Angular Material table?

When using Angular material to display a list, I am facing an issue where the content of the list is not being displayed but the header is. Component: export class CompaniesComponent implements OnInit { displayedColumns: string[] = ['id']; ...

Advanced type generics in Typescript

I've hit a roadblock in my attempt to ensure type safety for a function that should take an object and return a number. Despite numerous efforts, I haven't been successful. To give you a simple example (the actual application involves more comple ...

Acquiring cached data and integrating it into a module

Struggling to access an exported Cache in another file, but hitting roadblocks. Essentially, two files are involved: cache.ts Showcasing only the essential part import Cache = require('node-cache'); const narrativeCache: Cache = New Cache(); ...

How to dynamically modify ion-list elements with Ionic on button click

Imagine having 3 different lists: List 1: bus, plane List 2: [related to bus] slow, can't fly List 3: [related to plane] fast, can fly In my Ionic Angular project, I have successfully implemented the first ion-list. How can I dynamically change th ...

Update the component with the current route and state synchronization with react router dom

Is there a method to synchronize the active route in the browser with the component state? When I click on "Route 2" in the navigation bar, it gets highlighted as the active route and the browser URL shows "/route2". However, upon refreshing the page, "Ro ...

What is the appropriate return type for this function in TypeScript?

Seeking clarity on a fundamental TypeScript concept here. I've noticed that Google Cloud examples use JavaScript, and I'm in the process of converting one to TypeScript. Source: https://cloud.google.com/storage/docs/listing-buckets#storage-list ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

Converting a UUID String to a Number in React using Typescript: A Step-by-Step Guide

Currently, I am delving into the realm of React and Typescript. One intriguing challenge I encountered involves sending a URL containing a UUID parameter to another page through a GET request. The URL in question looks something like this: http://localho ...

Going through each file individually and addressing any issues

I have a folder with hundreds of files that I need to read. Currently, my method reads all the files at once and returns the content as an array. However, I want to optimize this process by reading one file at a time and sending it to the client before mov ...

Iterate through a collection of objects and organize the data in a specific way

Within the data structure of my API response, I am attempting to iterate through an array of objects under the items key. Each value inside these objects needs to be formatted based on the corresponding format type specified in the header key. To assist wi ...