What is the process of updating a displayed list by clicking on a button?

I have a requirement to showcase a list of individuals. Each individual has a set of team ids and roles. The displayed list should only include individuals with the role of "player" in the selected team.

It seems to be functioning correctly for the first team, but when I switch to another team, it either displays no one or just one person. What could be causing this issue?

export class HomeComponent implements OnInit {

  constructor(private personService: PersonService){  }

  ngOnInit() {
    this.getTeams();
    this.getPlayers();
  }

  getPlayers(){
    this.personService.getPersons().subscribe((persons: Person[])=>{    
      // set image if unset
      for(var i=0; i < persons.length; i++){
        if(persons[i]["image"] == ""){
          persons[i]["image"] = "assets/images/player.jpg";
        }
      }
      this.persons = persons;
    })
  }

  getTeams(){
    this.personService.getTeams().subscribe((teams: Team[])=>{
      this.teams = teams;
      this.selectedTeam = this.teams[0];
      this.load(this.selectedTeam);
    })
  }

  load(team:Team){
    if(this.selectedTeam.id != team.id){
      this.selectedTeam = team;
      console.log(this.selectedTeam);
    }
  }

}
@Pipe({
  name: 'PersonRole'
})
export class PersonRolePipe implements PipeTransform {

  public transform(persons: Person[], role: string) {
    return persons.filter(person => person.roles.includes(role) === true) as Person[];
  }

}
@Pipe({
  name: 'PersonTeam'
})
export class PersonTeamPipe implements PipeTransform {

  transform(persons: Person[], team: Team) {
    return persons.filter(person => person.teams.includes(team.id) === true) as Person[];
  }

}
<div id="teams-switch">
      <shape-button
        *ngFor="let team of teams"
        [label]="team.name"
        theme="accent"
        (click)="load(team)">
      </shape-button>
  </div>

  <ngx-slick-carousel 
    class="carousel"
    #slickModal="slick-carousel"
    [config]="slideConfig">

    <shape-person-card
    ngxSlickItem 
    *ngFor="let person of persons | PersonRole:'player' | PersonTeam:selectedTeam" 
    class="slide item"

    [tag]="person.tag"
    [name]="person.name"
    [image]="person.image"

    [socialmedia]="person.socialmedia">
    </shape-person-card>

  </ngx-slick-carousel>

Answer №1

It seems like the PersonRole and PersonTeam pipes you're using are acting as filtering pipes, potentially causing issues with detecting changes properly. Pipes are typically "pure," meaning they only run when the input changes. In this case, however, the input remains constant while only the parameters change.

To address this issue, consider moving the filtering logic to where it truly belongs - in your component:

filteredPersons = [];
filterPersons() {
  if (this.selectedTeam && this.persons) {
    // Using mutative method due to limitations of ngx-slick
    this.filteredPersons.length = 0;
    // Optimize by filtering players at the start when receiving persons array
    this.persons.filter(p => p.roles.includes('player') && p.teams.includes(this.selectedTeam.id))
                .forEach(p => this.filteredPersons.push(p));
  }
}

trackById(index, person){
  return person.id; // Utilize in trackBy
}

load(team:Team){
  if(this.selectedTeam.id != team.id){
    this.selectedTeam = team;
    console.log(this.selectedTeam);
    this.filterPersons();
  }
}

Your HTML should now be:

*ngFor="let person of filteredPersons; trackBy: trackById" 

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

How can I increase the number of input boxes dynamically when clicking a button?

I am currently working on developing a checklist application, and I'm facing a challenge with the functionality. The user should be able to add items by clicking a button which opens input boxes for item name and quantity. While this initial part work ...

Having trouble invoking the child component when the button is clicked

I am utilizing the ng-sidebar library. My goal is to trigger a child component (sidebar) when a button is clicked, but I am unable to achieve the desired result. For example: Check out this Stackblitz demo Parent TypeScript code: export class AppComponen ...

Having trouble with Vue i18n and TypeScript: "The '$t' property is not recognized on the 'VueConstructor' type." Any suggestions on how to resolve this issue?

Within my project, some common functions are stored in separate .ts files. Is there a way to incorporate i18n in these cases? // for i18n import Vue from 'vue' declare module 'vue/types/vue' { interface VueConstructor { $t: an ...

Is there a speedy and efficient method for rearranging a UI list?

Currently utilizing Angular 2 and Typescript. In my current project, I am displaying a basic list of JSON objects. The HTML structure is as follows: <div> <!-- List Presentation Button --> <button md-button (click)="showList( ...

Developing a bespoke React Typescript button with a custom design and implementing an onClick event function

Currently, I am in the process of developing a custom button component for a React Typescript project utilizing React Hooks and Styled components. // Button.tsx import React, { MouseEvent } from "react"; import styled from "styled-components"; export int ...

Avoiding the pitfalls of hierarchical dependency injection in Angular 6

Too long; didn't read: How can I ensure that Angular uses the standard implementation of HttpClient in lower level modules instead of injecting a custom one with interceptors? I have developed an Angular 6 library using Angular CLI. This library expo ...

Display a crimson undulating line beneath select words within the input field

I'm currently working on a component in React that involves using an input field to type query syntax, similar to (A=2 and B="Value2"). My goal is to highlight errors by displaying a red wavy line below objects that are incorrect, without affecting th ...

Tips for creating a draggable Angular Material dialog

Has anyone been able to successfully implement draggable functionality in an Angular Material Dialog? I've spent a considerable amount of time searching for a definitive answer but have come up empty-handed. Any insights or guidance would be greatly a ...

Retrieve Information in a List

I am currently facing an issue while trying to retrieve data from an array. Below is an example of the image array that I am working with. I am specifically looking to get the weather icon data, but unfortunately I encountered this error message: core.js:1 ...

When compiling TypeScript, the exported module cannot be located

I've encountered an issue while working on my TypeScript project. Upon compiling my code with the following configuration: { "compilerOptions": { "target": "ESNext", "module": "ESNext", & ...

What is the best way to transfer data from .ts and .html files to css/scss in an Angular

I'm currently working on a MEAN stack application and I would like to allow users to customize the theme color. The selected color should be saved in MongoDB so that every time the user opens the application, it remains consistent. I would appreciate ...

What sets template-driven and reactive forms apart in practice?

Exploring the Angular2 new Forms API has revealed two distinct approaches to forms: Template driven and reactive (model-driven) forms. I am curious about the real-world differences between these two methods, beyond just syntax. Which approach is more adva ...

Testing Angular application using Cypress.io with a Google Login popup window

Has anyone experienced difficulties logging into a Google account using Cypress.io and the Google authentication pop-up window? Although I am able to open the window, Cypress is unable to locate the ID for the email input field. The specific error messag ...

What is the most effective way to manage property assigned as `SomeType[] | unknown`?

When making an API call, I receive data with a property set to SomeType[] | unknown. This means my data structure looks something like this: interface SomeType { name: string enabled: boolean } interface MyData { id: string name: string someArra ...

Angular HTTP post promise is not functioning, whereas AJAX is working effectively

I am encountering an error while attempting to create a post using the code snippet below: short-form.component.ts this.shortFormService.update(formModel) .then(res => { this.router.navigate(['/goHere']) } ); short-for ...

Can someone please explain how to bring in the Sidebar component?

click here for image description check out this image info An issue arises as the module '@components/Sidebar' or its type declarations cannot be located.ts(2307) Various attempts were made, including: import Sidebar from '@components/Sid ...

"Unlocking the Power of Monaco Editor: A Guide to Fetching CompletionItems from Your

Currently, I have integrated the fantastic monaco editor into my Angular 8 app for editing formulas. Everything is working fine, but now I need the list of suggestions (CompletionItems) to update dynamically. I have utilized the ngx-monaco-editor module a ...

Assign a variable to set the property of a class

Could something similar to this scenario be achievable? const dynamicPropName = "x"; class A { static propName = 1 // equivalent to static x = 1 } A[dynamicPropName] // will result in 1 or would it need to be accessed as (typeof A)[dynamicPropN ...

elimination of nonexistent object

How can I prevent releasing data if two attributes are empty? const fork = [ { from: 'client', msg: null, for: null }, { from: 'client', msg: '2222222222222', for: null }, { from: 'server', msg: 'wqqqqqqqq ...

Remapping compound enum-like constant objects dynamically with type safety in TypeScript

I am currently developing a small utility that generates typesafe remapped object/types of compound enums. The term "compound" in this context refers to the enum (essentially a const object) key mapping to another object rather than a numeric or literal va ...