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 datatype 'string' cannot be assigned to the datatype '(token: string) => void'

Within my Angular2 application, I have a class that includes several properties which will be assigned values within components. @Injectable() export class Globals { private token: string; private authorization: string; private roleUser: boole ...

What is the process for performing type checking on an array variable designated as "as const"?

Check out this code snippet: export type Types = 'a' | 'b'; export type MyPartials = { readonly [P in keyof Types]?: number; }; export interface MyI { readonly name: string; readonly myPartials: MyPartials; } export const myI ...

Utilizing and transmitting contextual information to the tooltip component in ngx-bootstrap

I am currently working on integrating tooltips in ngx-bootstrap and trying to figure out how to pass data to the ng-template within the tooltip. The documentation mentions using [tooltipContext], but it doesn't seem to be functioning as expected. Belo ...

Upgrading to Angular 2: Utilizing ElementRef in ES5

Currently, I am facing a challenge in creating an Attribute directive for Angular 2 that would allow me to set multiple default HTML attributes using a single custom attribute. My intention is to apply this directive specifically to the input element. Howe ...

Binding an ID to an <ion-textarea> in Ionic 3

Can an ID be assigned to an ion-textarea? For example: <ion-textarea placeholder="Enter your thoughts" id="thoughtsBox"></ion-textarea> Thank you very much ...

Apologies, but it seems there was an issue with the installation of the "@angular/compiler-cli" package

Despite thoroughly searching through various threads, I am still unable to find a solution to my problem. I have cloned the angular2 quickstart project and ensured that all module versions are up to date. For reference, here is the link to the repository ...

What is the most efficient way to organize these arrays?

I've been racking my brain trying to figure out a sorting logic for some arrays, but I'm stumped. Maybe you have an idea? Imagine we have an array of objects structured like this: let obj = {day:'2', month:'6', year:'19 ...

Multiple Components Sharing the Same ID Attribute in Angular

Recently, I discovered that using the same id attribute for HTML elements in multiple components can lead to repetition of the ID in the DOM when those components are rendered together in the view. Let's consider the following scenario: //hello.comp ...

What is the best approach to modifying array elements using onChange and hooks in React?

I'm struggling to implement something simple, and the solutions I've found so far don't quite address my specific issue. Here's the state in question: const [formFields, setFormFields ] = useState({ formTitle: '', fiel ...

The functionality of the System JS map is not functioning properly

Despite the challenges I face with System.js, I find it to be a valuable tool that I prefer over alternatives. This is my current System.js configuration: System.config({ packages: { app: { format: 'register' ...

Loop through JSON results in Ionic using Angular

I am struggling to retrieve data from a JSON file in Object format using Typescript. When I try to fetch the data from the API, it doesn't display as expected. Typescript this.http.get('http://example.com/api') .subscribe((data) => { ...

"Simply click and drag the preselected item into the viewer to add it

I am looking to create an angular page with specific functionality: Enable users to upload a document (no problem) Display the document's content Allow users to drag a predetermined object onto the document display area to indicate where they will si ...

Is it possible to load the surrounding markup in Angular before the guards are resolved upon the initial load of the router-outlet?

Within our Angular 12 application, we have implemented guards that conduct checks through API calls to the backend in order to validate the user's permissions for accessing the requested route. The default behavior of these guards follows an all-or-no ...

Issue: Encounter of "Uncaught (in promise) TypeError" while implementing RiveScript chatbot in Angular

I've been working on integrating a chatbot based on RiveScript into Angular. The chatbot is functioning well - I always see the correct response in the console. Displaying the user's input is also working seamlessly. However, I'm encounterin ...

Using conditional styles with Angular 2

I am currently working on applying conditional styles to a table. For instance, if a user's "obsolete" property is true, I want to display their information with a <del> tag. I have searched online for solutions, and while I am aware of using *n ...

Can you point me in the direction of the Monaco editor autocomplete feature?

While developing PromQL language support for monaco-editor, I discovered that the languages definitions can be found in this repository: https://github.com/microsoft/monaco-languages However, I am struggling to locate where the autocompletion definitions ...

Console not logging route changes in NextJS with TypeScript

My attempt to incorporate a Loading bar into my NextJs project is encountering two issues. When I attempt to record a router event upon navigating to a new route, no logs appear. Despite my efforts to include a loading bar when transitioning to a new rout ...

Setting up Angular 2 on an Apache server for deployment

I am struggling to deploy my Angular 2 application on an Apache server despite following multiple guides such as this and this. I have both npm and ng installed on the server. This is what I have done so far: Cloned the entire project repository on my se ...

Date input using manual typing format

I've implemented the ng-pick-datetime package for handling date selection and display. By using dateTimeAdapter.setLocale('en-IN') in the constructor, I have successfully changed the date format to DD/MM/YYYY. However, I'm facing an iss ...

How to Programmatically Assign Bootstrap Class to an Element Using Angular 2

I am working on a page with several input boxes that need to be flagged for certain criteria. <div class="form-group"> <label class="d-block">Allowance Type</label> <div class="input-group"> ...