Trigger the identical event to be sent to two distinct functions upon the corresponding button click in Angular 2 using Typescript

I recently implemented a service that fetches JSON data and subscribes to two different variables within my component. These variables are then used by two separate drop-down lists to filter the data accordingly. The filtered data is then sent to another set of buttons, which can display the data as an array or a list. It is important that each drop-down operates independently.

<div class="TSO-ddl" >
    <md-select [(ngModel)]="selectedISO" (ngModelChange)="onSelect($event,selectedISO)" placeholder="TSO"  >
        <md-option  value="Charge Only"  > Charge Only </md-option>
        <md-option  value="PJM"  >PJM  </md-option>
        <md-option  value="Not in ISO Market"  > Not in ISO Market </md-option>
        <md-option  value="UCSD"  > UCSD </md-option>
        <md-option  value="Any" > Any </md-option>
    </md-select>
</div>

<div class="Status-ddl">
    <md-select [(ngModel)]="selectedStatus" (ngModelChange)="onSelect($event,selectedStatus)" placeholder="Status" >
        <md-option  value="NC"  >  Not Connected </md-option>
        <md-option  value="GI"  > Active  </md-option>
        <md-option  value="SLP"  >  Sleeping </md-option>
        <md-option  value="IA"  > Inactive  </md-option>
        <md-option  value="Any"  > Any  </md-option>
    </md-select>
</div>

<md-list-item class="ui-primary-selector"> 
   <div>  
       <label  class="labeltag"> View </label>
       <button md-button  *ngFor="let view of viewButtons "  [ngClass]="{'selected-item' :view === selectedView}" type="button" (click)="onClickView(selecctedISO,view); onClickView2(selectedStatus,view)">
        {{view.Name}} </button>
  </div>
</md-list-item>

TS file

    constructor(private vehicleService: VehicleService) {
        this.isoArray = [];
        this.statusArray = [];
        this.isoToShow = this.isoArray;
        this.statusToShow = this.statusArray;
    }

    ngOnInit() {
        this.vehicleService.getIVS()
            .subscribe(isoArray => {
                this.isoArray = isoArray;
                this.isoToDisplay();

            },
            error => this.errorMessage = <any>error);

        this.vehicleService.getIVS()
            .subscribe(statusArray => {
                this.statusArray = statusArray;
                this.statusDisplay();

            },
            error => this.errorMessage = <any>error);
    }


    viewButtons: IButton[] = [
        { Id: 1, Name: 'Array' },
        { Id: 2, Name: 'List' }
    ];

    onSelect(val, button: IButton) {

        if (val = "Charge Only" || "PJM" || "USCD" || "Not in ISO Market" || "Any") {
            this.selectedISO = val;
            this.onClickView(val, button)
        }
        else if (val = "NC" || "GI" || "SLP" || "IA") {
            this.selectedStatus = val;
            this.onClickView2(val, button);
        }
        console.log(val);
    }

    onClickView2(val, button: IButton) {

        this.selectedView = button;
        if (button.Id == 1) {
            val = this.selectedStatus;
            console.log(val);
            if (val === "Any")
            { this.statusToShow = this.statusArray; }
            else
            { this.statusToShow = this.statusArray.filter(resource => resource.primary_status === val); }


            //displays an array

        }
        else if (button.Id == 2) {
            val = this.selectedStatus;

            if (val === "Any")
            { this.statusToShow = this.statusArray; }
            else
            { this.statusToShow = this.statusArray.filter(resource => resource.primary_status === val); }
        }

        //displays a list
    }

    onClickView(val, button: IButton) {

        this.selectedView = button;
        if (button.Id == 1) {
            val = this.selectedStatus;
            console.log(val);
            if (val === "Any")
            { this.isoToShow = this.isoArray; }
            else
            { this.isoToShow = this.isoArray.filter(resource => resource.iso_id === val); }
            //displays an array

        }
        else if (button.Id == 2) {
            val = this.selectedStatus;

            if (val === "Any")
            { this.isoToShow = this.isoArray; }
            else
            { this.isoToShow = this.isoArray.filter(resource => resource.iso_id === val); }
        }
        //displays a list
    }

One challenge I am facing is that the event only gets sent to one of the functions, resulting in a null value for the other function. I am seeking guidance on how to ensure data is sent to both functions from the onSelect() when there is a corresponding value.

Answer №1

Invoke the second function from the first function and provide the event or any other desired parameter:

onSelect(val, button: IButton) {
  onSelect2(val, button);
  //perform some actions
}

onSelect2(val, button: IButton) {
  //perform some actions
}

Modification

To filter the dataset for displaying based on the selected value in md-select:

HTML

<div class="TSO-ddl" >
    <md-select (change)="onSelect($event)" placeholder="TSO"  >
        <md-option  value="Charge Only"  > Charge Only </md-option>
        <md-option  value="PJM"  >PJM  </md-option>
        <md-option  value="Not in ISO Market"  > Not in ISO Market </md-option>
        <md-option  value="UCSD"  > UCSD </md-option>
        <md-option  value="Any" > Any </md-option>
    </md-select>
</div>

Component

const data =[
     { iso_id: 'Charge Only',  name: 'Zero', status="NC" },
      { iso_id: 'Charge Only', name: 'Mr. Nice', status="NC" },
      { iso_id: 'PJM', name: 'Narco', status="IA" },
      { iso_id: 'PJM', name: 'Bombasto', status="IA" },
      { iso_id: 'PJM', name: 'Celeritas' , status="NC"},
      { iso_id: 'Not in ISO Market', name: 'Magneta', status="GI" },
      { iso_id: 'Not in ISO Market', name: 'RubberMan', status="SLP" },
      { iso_id: 'Not in ISO Market', name: 'Dynama' , status="GI"},
      { iso_id: 'UCSD', name: 'Dr IQ' , status="NC"},
      { iso_id: 'UCSD', name: 'Magma' , status="SLP"},
      { iso_id: 'UCSD', name: 'Tornado' , status="NC"}
    ];
displayList = Array<any>;

onSelect(val){
    if (val.value === 'Any'){
      this.displayList = this.data.slice();
    }else {
      this.displayList = this.data.filter(data => data.iso_id === val.value);
    }
  }

In essence, upon the change event, we trigger the method by passing the event, extract the selected option value from the event, and filter the data accordingly for display. It is recommended to fetch data for each iso_id from the service and dynamically populate the md-option values with the unique values obtained.

Access the updated working example on Plunker here

Answer №2

After some careful debugging, I finally pinpointed where my code was going off track.

onSelect(val, button: IButton) {

        if (val = "Charge Only" || "PJM" || "USCD" || "Not in ISO Market" || "Any") {
            this.selectedISO = val;
            this.onClickView(val, button)
        }
        else if (val = "NC" || "GI" || "SLP" || "IA") {
            this.selectedStatus = val;
            this.onClickView2(val, button);
        }
        console.log(val);
    }

It turns out that the comparison logic was flawed. I managed to correct the issue by adjusting the if statement as follows-

if (val = "Charge Only" || val ="PJM" || val ="USCD" || val = "Not in ISO Market" || val ="Any") {
                this.selectedISO = val;
                this.onClickView(val, button)
            }

A big thank you to the community for all the valuable 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

typescript locate within the union type in the mapping expression

Consider the following: type X = { label: 'Xlabel', X_id: 12 }; type Y = { label: 'Ylabel', Y_id: 24 }; type Z = { label: 'Zlabel', Z_id: 36 }; type CharSet = X | Y | Z; I am looking for type CharSetByLabel = Map<CharSet& ...

What is the best way to add multiple elements to an array simultaneously?

I am facing an issue with my array arrayPath. I am pushing multiple values into it, but there are duplicates in the data. When the value of singleFile.originalFilename is a duplicate, I do not want to push that duplicate value into arrayPath. How can I ach ...

Encountered an error loading resource: server returned a 404 status code while utilizing Angular framework and deploying via GitHub Pages

Currently facing an issue with my Angular website deployment on Github Pages, receiving a console error "Failed to load resource: the server responded with a status of 404 ()" at "home: 1". This error specifically seems to be related to the app.component ...

Angular 2 validation issue not functioning as anticipated

Here is a validator function that I have: export const PasswordsEqualValidator = (): ValidatorFn => { return (group: FormGroup): Observable<{[key: string]: boolean}> => { const passwordCtrl: FormControl = <FormControl>group.contr ...

I am having trouble loading the component; please direct me to the login page

Utilizing Angular 7 to develop an admin dashboard, I encountered an issue with the home page. The home page is supposed to load before logging in, but it only works after logging in. Prior to logging in, the page briefly appears for a second and then autom ...

Encountered a problem during the installation of firebase @angular/fire

I've been developing an Angular chat application and ran into some issues when trying to install Firebase using the command "npm install --save firebase @angular/fire". The installation resulted in a series of errors, with the main problem appearing t ...

Utilizing a file type validator in SurveyJs: A guide

Is there a way to validate uploaded documents on a form using surveyJs and typescript with a custom validator before the file is uploaded? The current issue I am facing is that the validator gets called after the upload, resulting in an API error for unsup ...

Compatibility of Typescript with local storage

Can Typescript interact with local storage in any way? I have been setting items using the following code: localStorage.setItem('someString', JSON.stringify(MyTypescriptObject)); This method stores the object as a plain string. For example: ...

Customize the text for the material icon

Can I customize an icon by using the following code: import FiberNewIcon from "@mui/icons-material/FiberNew"; Is there a way to add custom text to the icon? ...

The mat-paginator fails to display the page information

Material paginator is not displaying the page information correctly. In the official documentation, it shows the page info as 'Page 1 of 20', but when I run their code locally or on Stackblitz, the output is different. Instead, it shows the num ...

Creating a generic class in Typescript that can only accept two specific types is a powerful

When designing a generic class, I am faced with the requirement that a property type must be either a string or number to serve as an index. If attempting something like the code snippet below, the following error will be triggered: TS2536: Type 'T ...

What is the best way to structure YAML information in Angular version 14?

I am developing an Angular 14 Application where I have received YAML data in the API Response. I want to display it on my frontend, but the pre tag only shows plain text without any formatting, color, or line numbers similar to other websites I've see ...

Displaying nested web service array data in Angular 4

I created a project that retrieves data from a web service API. However, the API contains nested arrays that also need to be displayed. How can I access the data from these nested JSON arrays? What is the correct way to extract this data within the HTML co ...

How to extract and compare elements from an array using Typescript in Angular 6

I have created a new Angular component with the following code: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Compone ...

When you want to place an image in the middle of a cell, you can easily achieve this by utilizing the addImage function

I am currently utilizing the addImage() method within the exceljs library to insert an image into a cell of an Excel file that is exported from my Angular application. While I have successfully added the image using the addImage() method, it appears in t ...

Testing HTTP Requests in Angular applications

I am currently utilizing Angular 9+. When it comes to unit testing services that utilize httpClient for making http requests, I found the official documentation from the Angular Team to be very helpful. By following their guidelines, I was able to success ...

What could be causing the issue with "class not being recognized as a constructor" error that I am encountering?

When attempting to create an instance from modules in routing, I consistently encountered the error message "class is not a constructor." Below is the code snippet: export class Modules{ modules : object = { masterdata : MasterdataModule, shop : ...

Unable to retrieve HTTP call response during debugging, although it is visible in the browser

When I send an HTTP request to create a record, I am able to see the added record id in the Network section of browsers like Chrome and Firefox. However, when I try to debug the code and retrieve the same id value, I encounter difficulties. I have tried us ...

Error: An unauthorized attempt was made to modify property settings for certain users, which are designated as read-only

Within my Ionic app, there exists a specific page where users have the ability to modify information related to a particular city. What I aim to achieve is for these modifications to only be visible to other users who are also located within the same "City ...

What factors should I consider when determining whether to include @types/* in the `dependencies` or `devDependencies` section?

Currently using TypeScript 2 in my project, I am looking to incorporate a JavaScript library along with its typings. While I know I can easily install the types using npm install @types/some-library, I am uncertain whether to use --save or --save-dev. The ...