Implement a feature that allows users to easily reset applied filters by clicking a button, but currently experiencing issues with the functionality

How to create an HTML button

<button
  id="styleButton"
  class="ml-2 refreshButton"
  (click)="removeAllFilters(appliedFilters)"
>
<i class="fas fa-sync-alt"></i>
</button>

JavaScript function for removing all filters

removeAllFilters() {
        this.appliedFilters = [];

        this.searchText = '';

        this.status.map(item => {
            if (item.name !== TypeStatus.ACTIVE) item.selected = false;
        });

        this.locations.map(item => (item.selected = false));

        this.roles.map(item => (item.selected = false));
    }

I attempted to implement the remove all filters function, but it is not functioning properly.

Answer №1

When using the map method, it is important to note that it does not alter the original array, but rather creates a new array with the desired modifications.

As a result, there are two options available to address this issue;

1. Replace map with forEach

removeAllFilters() {
        this.appliedFilters = [];
        this.searchStaffText = '';
        this.status.forEach(item => {
            if (item.name !== StaffTypeStatus.ACTIVE) item.selected = false;
        });
        this.locations.forEach(item => (item.selected = false));
        this.roles.forEach(item => (item.selected = false));
    }

2. Assign the modified arrays returned by the map method back to the original arrays.

removeAllFilters() {
        this.appliedFilters = [];
        this.searchStaffText = '';
        this.status = this.status.map(item => {
            if (item.name !== StaffTypeStatus.ACTIVE) item.selected = false;
            return item;
        });
        this.locations = this.locations.map(item => {
            item.selected = false;
            return item;
        });
        this.roles = this.roles.map(item => {
            item.selected = false;
            return item;
        });
    }

Answer №2

Initially, in your HTML file, you are invoking the function removeAllFilters(appliedFilters). However, it seems that the parameter appliedFilters is not defined in your TypeScript code.

Furthermore, there is an issue with how you are using the map method. Remember that every map function must have a return statement. Here is an example to illustrate this:

removeAllFilters() {
        this.appliedFilters = [];

        this.searchStaffText = '';

        this.status = this.status.map(item => {
            if (item.name !== StaffTypeStatus.ACTIVE) item.selected = false;
            return item; // MAKE SURE TO ADD A RETURN STATEMENT
        });

        this.location = this.locations.map(item => {
            item.selected = false;
            return item; // MAKE SURE TO ADD A RETURN STATEMENT
        });

        this.roles = this.roles.map(item => {
            item.selected = false;
            return item;
        });
    }

Best regards, Flo

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

Issue with importing Control in Ionic 2 leads to errors

I am encountering an issue when trying to import Control for email Validator in my Ionic 2 RC0 project. Below is the code snippet: /** * Created by adirz on 10/14/2016. */ import { Control } from '@angular/common'; export class EmailValidator ...

Angular has a way of causing confusion when it comes to differentiating between anchor scrolling and wildcard routing, denoted by

I am facing an issue in my Angular project where anchor scrolling is conflicting with wildcard routes. Here is what I have done in the project: I have enabled anchor scrolling in my app.module.ts like this: RouterModule.forRoot( [ { path: &ap ...

Exchange a TypeScript data type with a different one within an object

I am currently working with the following type definitions: type Target = number | undefined; type MyObject = { some: string; properties: string; id: Target; } I am trying to find a generic solution to replace instances of Target with number ...

Angular 8: Implementing functionality for the Parent Component to detect when the User clicks outside of the Child Component Textbox

I am working on a scenario where I have a Parent Component and a Child Component containing a Formbuilder and a ZipCode textbox. Is there a way to notify the Parent Component when the user clicks out of the Child Component Textbox? I need to trigger some ...

I'm looking to transform this array into the format described below, and also include another nested subarray within it using TypeScript

[{ "header": "API", "value": "hello" }, { "header":"API", "value":"yellow" }, { "header":"Other", "value":"yallow"}, { "header":"other", "value":"othertt" } ] I have a list of objects with he ...

Angular 2 applications with routing capabilities running within nested iframes

Currently, I am in the process of developing an Outlook add-in using Angular 2. Since it is an outlook hosted app, it will be run within a cross-domain iframe and I have no control over this setup. The iframe is also sandboxed with specific properties incl ...

There seems to be some odd behavior with the HTTPInterceptor in Angular 7

I have an interceptor that catches errors and logs the output to the console: intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request).pipe( catchError((error: HttpErro ...

The switchMap function in Angular does not trigger the async validator as expected

To ensure that the username entered by the user is unique, I am sending an HTTP request for every input event from the target element. It is important to debounce this operation so that only one HTTP request is made for X consecutive input events within a ...

Comparing Angular2 and Webpack: Choosing between i18n plugin or ng2-translate

Looking to develop a web application using Angular2 and bundling it with webpack. What is the most effective method for incorporating multiple languages? Option 1: i18n-plugin - Check it out here or Option 2: ng2-translate - Find more information here ...

Why does the Angular asyncScheduler test fail when using flush()?

Consider this Angular component: import { Component, OnDestroy, OnInit } from '@angular/core'; import { asyncScheduler, Observable, of, queueScheduler, scheduled } from 'rxjs'; @Component({ selector: 'test-component', te ...

How do I go about creating shades when working with material theming?

Hello everyone! I am interested in developing a unique theme with Angular Material theming, incorporating my own set of three colors. Typically, the Angular Material themes are defined with shades like this: $mat-red: ( 50: #ffebee, 100: #ffcdd2, 20 ...

What is the process for displaying an error message in a component.ts file?

Is there a way to receive error messages in my component.ts file? How can I display the service class error message on an HTML page? Component.ts Method: addNew(): any { this.apiService.addIndexReference(Data.AccessToken,this.indexReference,this.inde ...

Customizing key values within nested objects in Angular2: A comprehensive guide

I need assistance with setting up a JSON object for a post in Angular2/Typescript. I am trying to dynamically set the nested object values for a key. Is it possible to achieve this using Angular2/Typescript? I have attempted to retrieve the values from JS ...

Ways to enforce a specific type based on the provided parameter

Scenario Background: // Code snippet to do validation - not the main focus. type Validate<N, S> = [S] extends [N] ? N : never; // Note that by uncommenting below line, a circular constraint will be introduced when used in validateName(). // type Val ...

Incorporating aws-sdk into Angular 2 for enhanced functionality

I'm currently working on integrating my Angular2 application with an s3 bucket on my AWS account for reading and writing data. In the past, we used the aws-sdk in AngularJS (and most other projects), so I assumed that the same would apply to Angular2 ...

The issue of Angular 4 routerLinkActive failing to apply the active class has users

I am struggling to style the css and add a class when a link is active using routerLinkActive. Despite success with Bootstrap, when I received custom CSS from the front end developer, the active class fails to be added, even when the route URL matches the ...

Acquiring the handle of ngComponentOutlet

I am dynamically creating a component using ngComponentOutlet. Here is an example: import {Component, NgModule} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' @Component({ selector: 'alert-success& ...

Discover the Prisma findMany method for implementing tanstack react table functionality

I'm looking to build a table (using tanstack table) populated with data fetched from Prisma.findMany. Let's suppose I have a User model: model User { id Int @id @default(autoincrement()) name String age String email String } Now, in my p ...

IE11 causing issues with Bootstrap/Angular dropdown functionality

Is there a workaround for the issue with the selected menu item not showing in IE11 for this simple drop-down? <div class="form-group program-container"> <select class="form-control container-fluid" (change)="onChooseMe ...

Error encountered when retrieving WordPress posts through GraphQL in Next.js due to an invalid `<Link>` containing a `<a>` child element

While integrating Wordpress posts into my Next.js application using the repository "https://github.com/vercel/next.js/tree/canary/examples/cms-wordpress", I encountered the error message: "Error: Invalid with child. Please remove or use ." https://i.ss ...