Ways to showcase information based on the chosen option?

Is there a way to display data based on the selected value in a more efficient manner? Currently, when clicking on a value from the list on the left side, new data is added next to the existing data. However, I would like the new data to replace the existing data each time a different value is clicked. Here's a visual representation of the current setup. https://i.sstatic.net/67lSq.png

I need help with improving this line of code (this.filteredСosts.push(c)) so that the data is not simply added alongside the existing data, but replaced when a new value is chosen.

  reports: Reports[]
  income: Income[]
  costs: Costs[]
  selectedReport = null
  filteredIncome = []
  filteredСosts = []

  onSelectedReport(reportId) {
    this.selectedReport = this.reports.find(
      el => {
        return el.report_id === reportId
      }
    )
    if (this.incomeService) {
      this.incomeService.fetchAll().subscribe(
        income => {
          this.income = income
          this.filteredIncome = this.income.filter(
            (income) => income.income_id == this.selectedReport.r_income_id
          )
          if (this.costsService) {
            this.costsService.fetch().subscribe(
              costs => {
                this.costs = costs
                for(let i of this.filteredIncome){
                  for(let c of costs){
                    if(c.costs_id==i.i_costs_id){
                      this.filteredСosts.push(c)
                    }
                  }
                }
              }
            )
          }
        }
      )
    }
  }

Here is how the html structure looks:

<div class="row">
  <div class="col s12 m2">
    <mat-list>
      <h3 mat-subheader>Date</h3>
        <mat-nav-list>
          <mat-list-item *ngFor="let report of reports" class="center " (click)="onSelectedReport(report.report_id)">
            <a>{{report.report_date | date: 'dd.MM.yyyy'}}</a>
          <mat-divider></mat-divider>
        </mat-list-item>
      </mat-nav-list>
    </mat-list>
  </div>
  <div class="col s12 m10">
    <div  *ngIf="selectedReport">
      <div *ngFor="let i of filteredIncome">
        <div *ngFor="let c of filteredСosts">
          {{c.name}}
        </div>
      </div>
    </div>
  </div>
</div>

Answer №1

Attempt to empty

this.clearedExpenses = [];

Answer №2

Make sure to set up this.filteredСosts right from the start.

      if (this.costsService) {
        this.costsService.fetch().subscribe(costs => {
          this.filteredСosts = []
          ...

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 ngStyle function in Internet Explorer

Within my Angular 4 application, I have defined styles as shown below: [ngStyle]="{'border': getInterleaveColor(i)}" The following function is also included: getInterleaveColor(auditNumber) { var borderProperties = '2px solid'; ...

Once the Angular project has been initialized, the Button disable attribute cannot be modified

In my Ionic-Angular project, I am creating registration pages where users input their information in multiple steps. For each step, there is a button that remains disabled until the correct information is entered. An issue arises when transitioning to the ...

How is it possible for TypeScript to enable the importing of dependencies that it ultimately cannot utilize during runtime?

Take a look at my sample project by following this link: https://github.com/DanKaplanSES/typescript-stub-examples/tree/JavaScript-import-invalid I have developed a file named main.ts: import uuid from "uuid"; console.log(uuid.v4()); While type ...

"Creating a Typescript property that is calculated based on other existing properties

I am working on a Typescript project where I have a basic class that includes an `id` and `name` property. I would like to add a third property called `displayText` which combines the values of these two properties. In C#, I know how to achieve this using ...

How can we transfer a value from a parent component class to a child subclass?

In my TypeScript file, there are three classes within a single file. I am attempting to transfer a value from the MainComponent class to the TableContent class. I initially tried using super() inside the TableContent class which did not work, and then att ...

Step-by-step guide to initializing data within a service during bootstrap in Angular2 version RC4

In this scenario, I have two services injected and I need to ensure that some data, like a base URL, is passed to the first service so that all subsequent services can access it. Below is my root component: export class AppCmp { constructor (private h ...

Tips for identifying two mat-tables within the same component in Angular UI

Having trouble with rendering rows in two mat-tables within the same component. The renderRows() function is not working for the second table. @ViewChild(MatTable) tagsTable: any; @ViewChild(MatTable) serviceAreaTable:any; this.tagsTable.renderRows(); # ...

Troubleshooting issue: Angular 7 navigation function not functioning within an 'if' statement

AppComponent.ts if(result['status'] === 'success'){ this.router.navigate(['/dashboard']) //return false alert("Login successful!"); } else { alert("Invalid login credentials"); } The "Login successful!" aler ...

Try out Playwright for testing Angular form controls

I'm currently examining a form control using the Playwright framework. The structure of the DOM is as follows: <div class="form-group"> <label for="usernameInput">User name</label> <input type="text" ...

Uploading multiple files simultaneously in React

I am facing an issue with my React app where I am trying to upload multiple images using the provided code. The problem arises when console.log(e) displays a Progress Event object with all its values, but my state remains at default values of null, 0, and ...

Fixing errors with observables in an Angular 2 project using Rx

var foo = Observable.create(function(observer){ try{ console.log('hey there'); observer.next(22); throw new Error('not good at all'); setTimeout(function(){ observe ...

When using Typescript, I am encountering an issue where declared modules in my declaration file, specifically those with the file

One of the declarations in my ./src/types.d.ts file includes various modules: /// <reference types="@emotion/react/types/css-prop" /> import '@emotion/react'; import { PureComponent, SVGProps } from 'react'; declare mod ...

Ways to retrieve a value from a span using the Document Object Model

sample.html <span id='char'>{{value}}</span> sample.ts console.log((<HTMLInputElement>document.getElementById('char'))) This code snippet will display <span id='char'>ThisIsTheValueupdated</sp ...

Showing JSON object in an Angular 2 template展示JSON对象在模

When I execute the following code: stanservice.categoryDetail(this.params.get('id')) .then((data) => { this.category = JSON.stringify(data.res.rows[0]); console.log(JSON.stringify(data.res.rows[0])); }) .catch((error) => { ...

The CORS policy is causing a blockage for the front-end application due to the Spring Boot backend

Currently working with Spring Boot and Angular. I have included the cross-origin annotation in my code to allow access from my Angular localhost port, but unfortunately, I am still encountering the following error: https://i.sstatic.net/4uDuv.png Here is ...

Using interpolation brackets in Angular2 for variables instead of dots

I'm curious if Angular2 has a feature similar to the bracket notation in Javascript that allows you to use variables to select an object property, or if there is another method to achieve the same functionality. Here is the code snippet for reference ...

Exploring the integration of SendGrid with Angular and NodeJS

Struggling to send an email using Angular and SendGrid. The NPM package is installed correctly, but I'm facing challenges with code implementation. Generated API key stored in directory: echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > se ...

What is the proper method for utilizing an object as a dependency when using useEffect?

Currently, I am in the process of developing a react hook that takes in a query object. export function useMyQuery(query: QueryObjectType) { React.useEffect(executeQuery, [ query ]); // ... } Unfortunately, whenever my hook is called during a re- ...

Angular2 routing does not trigger the Component constructor and Router life-cycle hooks when the router.parent.navigate method is called from a child component

I am currently working on an application that includes child routes. The parent component (App component) consists of 2 routes: @RouteConfig([ { path: '/overview', name: 'Overview', component: OverviewComponent, useAsDefault:true }, { ...

"Successful deletion with Express, yet error message of 'Not Found' displayed

I've implemented this boilerplate to build my API, utilizing express and typeorm with typescript. When attempting to delete a question, the deletion process works smoothly but I receive a 404 not found response. Below is my Question.ts class: @Entit ...