ANGULAR: Issue with filtering an array by clicking a button is not functioning

I've been attempting to apply a filter to my array by using modulo on the id when clicking multiple buttons. I initially tried using pipe but was advised to stick with .filter(). Despite watching numerous online tutorials, I keep encountering errors or complex solutions that don't quite fit my needs. Could it be that I am heading in the wrong direction for a straightforward onclick filter? As a newcomer to Angular, I find myself struggling with this concept.

import { Component, OnInit} from '@angular/core';
import { StreamService } from '../stream.service';
import { Stream } from '../stream';
import { map } from 'rxjs/operators';


@Component({
  selector: 'app-discover',
  templateUrl: './discover.component.html',
  styleUrls: ['./discover.component.scss']
})
export class DiscoverComponent implements OnInit {
  streams!: Stream[];
  
  constructor(private streamService: StreamService) { 
    
  }

  ngOnInit() {
    this.getStreams();
  }

  getStreams(){
    this.streamService.getStream().subscribe((data =>{
      this.streams = data;
      console.log(this.streams);
    }))
  }

  sortBack(){
    this.streams.sort((a, b) => a.id - b.id);
  }


  filterIsUneven(){
    this.streams.filter(stream => stream.id % 3)
  };
  
  

}
<div class="container">

  <div class="buttons">
    <button (click) = "filterIsUneven()"> Games </button>
    <button> Music </button>
    <button> Esports </button>
    <button> IRL </button>
    <button>Back</button>
  </div>

  <div class="streams" *ngFor="let stream of streams">
    <h3>{{stream.id}}</h3>
    <h3>{{stream.title}}</h3>
    <img src="{{stream.thumbnailUrl}}">
  </div>

</div>
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Stream } from './stream';
import { Observable} from 'rxjs';
 
@Injectable({
  providedIn: 'root'
})
export class StreamService{

constructor(private http: HttpClient) { }

getStream():Observable<Stream[]>{
  return this.http.get<Stream[]>("https://jsonplaceholder.typicode.com/albums/1/photos");
  }

getLiveStream(id:number):Observable<Stream[]> {
  const url = `https://jsonplaceholder.typicode.com/albums/1/photos?id=${id}`;
  return this.http.get<Stream[]>(url);
  }
}


Answer №1

To correct your filtering process, make sure to assign the result like this:

filterIsUneven(){
  this.streams = this.streams.filter(stream => stream.id % 3)
};

The issue with the initial approach is that it permanently alters the original list, making it impossible to revert back. To handle this, create a new list:

getStreams(){
  this.streamService.getStream().subscribe((data =>{
    this.filteredStreams = data;
    this.streams = data;
    console.log(this.streams);
  }))
}

filterIsUneven(){
  this.filteredStreams = this.streams.filter(stream => stream.id % 3)
};

Afterwards, utilize filteredStreams in your HTML instead of streams

Answer №2

"When using the filter() method, a new array is generated containing only the elements that meet the conditions specified in the function."

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

To implement this, you will need to update the this.streams property:

  filterIsOdd(){
    this.streams = this.streams.filter(stream => stream.id % 3)
  };

This approach may be suitable for your current situation, but keep in mind that it is irreversible. Consider creating a new property called this.filteredStreams, initializing it with the original values, applying your filters, and utilizing it in the ngFor loop for display.

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 TypeScript in the React-Native app is lacking certain properties compared to the expected type

I recently integrated the https://github.com/react-native-community/react-native-modal library into my project and now I need to create a wrapper Modal class. Initially, I set up an Interface that extends multiple interfaces from both react-native and reac ...

What is the process of saving an empty array as a property of a nested object in Mongoose?

Here is a snippet of the code I am working with: const newLesson = new Lesson({ classroomId: req.params.classroomId, name: req.body.name, startDate: startDate1, endDate: endDate1, ...

Exploring the Power of SectionList in Typescript

How should SectionList be properly typed? I am encountering an issue where this code works (taken from the official documentation example): <SectionList renderItem={({item, index}) => <Text key={index}>{item}</Text>} renderSectionHea ...

Checkbox selection can alternate based on conditions for formgroup controls

My FormGroup named 'fruits' has been set up fruits: FormGroup = formBuilder.group({ numberOfFruits: [0,Validators.min(0)], apple: false, mangoes: false }); Here is the corresponding HTML code: <div formGroupName ...

Utilizing Form Validation in Angular 4

In the process of developing a straightforward Angular application that utilizes Twitter Bootstrap and jQuery to showcase employee data. I have hardcoded 4 sets of data which are displayed in a table, as shown in the attached image. The addition of an "Add ...

Issue with tooltip not displaying attribute data-bs-title in Angular 17 with Bootstrap version 5.3

I am currently developing an Angular version 17 application and implementing a dynamic tooltip feature. The tooltip content will be supplied through a @Input() into the component. While a static tooltip works fine, I am facing an issue when trying to make ...

What is the best way to arrange a collection of JObjects in VB.net?

Currently, I am working with VB.net (4.5) and utilizing the Newtonsoft Json Linq package. Within my code, there is an array named BuyList that consists of 100 market orders structured as follows: {{ "Quantity": 0.14333804, "Rate": 6693.01 }} My obje ...

Populate a vacant buffer in C++ with a specific value

Excuse me if my terminology isn't entirely correct, I'm still getting the hang of C++ programming. I've developed a class that includes a constructor responsible for initializing an empty buffer using malloc LPD6803PWM::LPD6803PWM(uint16_t ...

Displaying an array object within an array of objects in Angular 2: A guide

Here is an example of a JSON file: { "id": 5, "url": "http://localhost:8000/api/v1/users/5/", "username": "Najmuddin", "email": "", "groups": [ { "id": 1, "url ": "http://localhost:8000/api/v1/groups/1/", ...

Using an Angular variable in a JavaScript function may seem challenging at first, but with

Currently, I have an Angular component that utilizes a JavaScript library (FullCalendar V4). The library triggers a function when certain events occur (such as mouseover or click) and provides an argument that allows me to access the calendar values (start ...

Choose images at random from an array within a React Native application

I've been working on a feature that involves randomly selecting an image from an array of images. However, I keep running into the issue of getting an "invalid props source supplied to image" error. My goal is to display a different random image each ...

The module 'angular/common' was not found in the Angular 2 TypeScript

While experimenting with a sample login form in Angular 2, I encountered an issue when trying to import 'Form_Directives' as: import { FORM_DIRECTIVES } from '@angular/common'; An error was displayed stating that the angular/common m ...

Changing return values with Jest mocks in TypeScript

Here I am again with a very straightforward example. In summary, I require a different response from the mocked class. Below is my basic class that returns an object: class Producer { hello() { return { ...

Using Angular 2 to assign unique ids to checkbox values

Is there a way to retrieve the value of a checkbox in Angular 2 without needing an additional Boolean variable? I am trying to toggle the enabled/disabled state of an input field based on the selection of a checkbox. While I know this can be accomplished ...

Error encountered when attempting to run an Angular 2 application with 'ng serve' command

Initially, I installed angular-cli using the command npm install -g angular-cli and then proceeded to create an angular-cli project. Following that, I used the command ng new Angular2TestProject to create a project and changed the directory to Angular@Test ...

Using React Query's useMutation hook may result in an error message of "No overload matches this call"

When incorporating react-query into my typescript project, I encountered a perplexing type error while attempting to utilize the useMutation() hook with a graphql query. Here is an example of the code: useMutation( async ( parameter1: string, ...

Leveraging the outcome of an Observable in one method with another Observable in Angular2

The issue at hand I am facing difficulty in utilizing the value returned by the Observable from getUserHeaders() within my http.get request. Error encountered Type 'Observable<void>' is not assignable to type 'Observable<Particip ...

Guide on utilizing a module in TypeScript with array syntax

import http from "http"; import https from "https"; const protocol = (options.port === 443 ? "https" : "http"); const req = [protocol].request(options, (res) => { console.log(res.statusCode); }); error TS2339 ...

Creating a TypeScript generic record with specified keys

I need to validate in TypeScript whether an object contains the specified keys (from SingleShopColumns or MultishopColumns) and has a validations property that is an array of strings. I am using Record and generics, but any simple method of representing t ...

Experiencing an "Invalid write of size 8" error when running Valgrind

I am encountering a puzzling "Invalid write of size 8" error in my multi-threaded Qt application developed in C++ on Ubuntu 14.04 while using valgrind. Take a look at the snippet from my code: // Allocate memory for arrays deltas = new double[time_count] ...