Angular feature that enables the use of multiple filter values at once through pipes

Using *ngFor, buttons are dynamically generated to filter by different values. For example, if the key 'location' has values 'west' and 'england', buttons for both 'west' and 'england' will be available for filtering.

The requirement is to enable selecting multiple filters. When 'england' is clicked, only results for 'england' are shown. Then, clicking on 'west' should display results for both 'west' and 'england' while keeping 'england' active. Currently, only one filter can be applied at a time.

A possible solution could involve assigning an active class to the button, which will update an array of active filters to send to the pipe for filtering.

Filter Button Setup

<div ngDefaultControl [(ngModel)]="filteredLocation" name="locationFilter" id="locationFilter">
    <button value="All" class="m-2 btn btn-primary" type="button">All</button>
    <button [class.active]="selectedIndex === i" (click)="filteredLocation = entry.location" class="m-2 btn btn-primary" type="button" *ngFor="let entry of timeLine | filterUnique; let i = index">{{entry.location}}</button>
  </div>

Single Filter Implementation on Results

<div class="timeline">
  <my-timeline-entry *ngFor="let entry of timeLine | filter:filteredLocation:'location'" timeEntryHeader={{entry.year}} timeEntryContent={{entry.detail}} timeEntryPlace={{entry.place}} timeEntryLocation={{entry.location}}></my-timeline-entry>
</div>

I've set up a stackBlitz demo showcasing the current behavior. You'll notice that only one filter can be applied at a time. Any suggestions or solutions would be greatly appreciated. Thank you!

Answer №1

If you want to determine if a location is active, one approach is to add a property like isLocationActive.

You can then toggle this flag as needed and apply the active class without using a filter pipe.

Here's how your HTML code could look:

<div class="form-group row">
  <div ngDefaultControl [(ngModel)]="filteredLocation" name="locationFilter" id="locationFilter">
        <button value="All" class="m-2 btn btn-primary" (click)="activeAllEntries()" type="button">All</button>
        <button [class.active]="entry.isLocationActive" (click)="entry.isLocationActive = !entry.isLocationActive" class="m-2 btn btn-primary" type="button" *ngFor="let entry of timeLine | filterUnique; let i = index">{{entry.location}}</button>
      </div>
</div>

<div class="timeline">
  <ng-container *ngFor="let entry of timeLine">
<my-timeline-entry *ngIf="entry.isLocationActive" timeEntryHeader={{entry.year}} timeEntryContent={{entry.detail}} timeEntryPlace={{entry.place}} timeEntryLocation={{entry.location}}></my-timeline-entry>
  </ng-container>

</div>

TS function

   activeAllEntries() {
      this.timeLine.forEach(t=> t.isLocationActive=!t.isLocationActive)
   }

Check out the working demo here!

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

When the page is refreshed, the route fails to load the data

My Vue.JS website is quite simple, utilizing VueX and Vue-Router. I have defined two routes: '#/' and '#/account/' These routes are filled with components from .vue files, loaded dynamically upon page load using http-vue-loader (to avo ...

Screen goes dark after switching to full-screen mode (panolens.js/three.js)

Utilizing a library known as panolens for displaying a 360-degree panoramic view, hinging on three.js. Within my application, there are two views: one containing custom content and the other serving as a container for panolens. Initially, the first view is ...

Harnessing the power of data within different components

In my setup, I have two vital components in play. The initial one is responsible for presenting a list of items, while the second dictates the design and layout of these items. These items reside in an array located within the app.vue file. Here lies my p ...

Incorporating a personalized jQuery slider into the website

Just starting out in front-end development and feeling a bit lost with jQuery. I have a custom step jQuery slider, but I'm struggling to make the output sync with the rest of my project. I believe I need to use .addEventListener('input') to ...

What is the best way to retrieve a random amount of lines of data from the stdin in Node.js?

Currently, I am attempting to execute a basic program in the Visual Studio Code terminal using node.js. This program involves reading inputs from the user, performing operations on those inputs, and displaying the results. Despite trying various methods, ...

Encountering an error in TypeScript and ng2 rc.1: Error message (20, 15) TS2304 indicates that the name 'module' cannot be found

Having trouble with TypeScript and ng2 rc.1 - getting Error:(20, 15) TS2304: Cannot find name 'module'. I encountered this issue when trying to use a directive of the module in my code: @Component({ selector: 'Notes1', moduleI ...

Using jQuery, identify when any of the elements within every function are missing

In my JavaScript file, I have the following code snippet: var aryYears= []; $(".year").each(function(){ aryYears.push($(this).val()); }) This allows me to pass an array of years as a parameter in the saveChanges function. I want to make ...

Angular2 - Model not being refreshed by Directive

I have implemented a directive on an HTML input box to handle numeric values. The directive is meant to "clean" the number (removing commas, dollar signs, etc) when a user pastes a number into the textbox. Although the cleaning code works properly, the iss ...

Information gathered from checkboxes and dropdown menus

When gathering information from my form fields, I know how to capture data from input fields using this code: 'formData' : { 'timestamp' : '<?php echo $timestamp;?>', 'token' : '<?php echo md5(&a ...

Evolutionary JavaScript Adaptations

I am currently working on an HTML project that involves the use of JavaScript with JQuery. In my project, I will be including a map showcasing different images such as 'Abstract', 'Animals', 'Beach' and more. var images = { & ...

Can an excessive amount of classes cause my Angular application to run sluggishly?

Within my Angular 7 application, I have generated approximately 200 to 300 classes for model types (e.g. component.model.ts) solely for type checking purposes. I have not instantiated any objects from these classes. As I navigate through the application, ...

Angular not firing slide.bs.carousel or slid.bs.carousel event for Bootstrap carousel

I've searched high and low with no success. I'm attempting to detect when the carousel transitions to a new slide, whether it's automatically or by user click. Despite my numerous attempts, I have been unable to make this event trigger. I ha ...

What is the best way to store and serve the AngularJS library locally in a static manner?

I have a project in Angular that needs to be developed without an internet connection, which means the CDN links will not work. I want to save the AngularJS library to a directory within my project. This is what I attempted: First, I visited the CDN link, ...

Tips for accessing JSON data stored as keys within a JavaScript object

I'm facing an issue with my Node.js lambda function that involves parsing JSON data received from an external application. The JSON data seems to be malformed and arrives as an object key, shown below: console.log(req.body) This results in: { &apo ...

Awaiting Node.js/Mongoose to patiently loop through asynchronous tasks

I have a question that might be quite basic for some. I am working with an array in my mongodb database and need to query/find multiple elements from it. My goal is to set an error variable to true if at least one element passes an if-statement. However, ...

Is there a way for me to manually initiate a digest cycle on the parent scope based on my instructions?

I am struggling with getting a directive to render automatically when a change is made to the underlying model programmatically. Using $scope.$apply seems like the right approach, but unfortunately it's not working as expected. The directive only rend ...

I'm curious, does a specific event get triggered when an item is added to a UL element?

Is there an event that gets triggered when a new item is added to a UL list? I am on the lookout for something like this. Thank you! ...

Whenever I attempt to run the NPM install command in the Terminal, it seems to generate multiple errors

I am encountering an issue on my work laptop. I have the latest versions of Angular, Nodejs, Nodesass, and VScode installed in the local environment path. Whenever I download an Angular template from Github and try to do NPM Install, it consistently thro ...

React encountered an error: Unable to destructure the property 'id' of '_ref' as it has been defined

After spending several hours trying to solve this issue, I am completely stuck. The console shows that the patch request successfully updates the information, but then my map function breaks, leading to a blank page rendering. Here is the problematic comp ...

Guide on creating a similar encryption function in Node JS that is equivalent to the one written in Java

In Java, there is a function used for encryption. public static String encryptionFunction(String fieldValue, String pemFileLocation) { try { // Read key from file String strKeyPEM = ""; BufferedReader br = new Buffer ...