Achieving selective exclusion of specific keys/values while iterating through an array and rendering them on a table using Angular

Currently facing a hurdle and seeking advice

I am developing an angular application that fetches data from an API and presents it on the page

The service I am utilizing is named "Api Service" which uses HTTPClient to make API calls

apiservice.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';


@Injectable({
  providedIn: 'root'
})

export class ApiserviceService {

constructor(private _http:HttpClient) { }

getData(){

return this._http.get('APIURL');
}

}

Additionally, I have another component that observes this call and maps the data to an array

data.component.ts

import { Component, OnInit } from '@angular/core';
import { map, toArray } from 'rxjs';
import { ApiserviceService } from '../apiservice.service';

@Component({
  selector: 'app-data',
  templateUrl: './data.component.html',
  styleUrls: ['./data.component.scss']
})
export class VenueComponent implements OnInit {

  
  data: any = [];

  constructor(private service:ApiserviceService) {}

    MapData() {
        this.service.getData().subscribe(result=>{
        this.data=result;
        console.log(this.data);
})
  }


 ngOnInit() {
    this.MapData()
  }




}

The data is then displayed in a table

data.component.html

<table>
    <tr *ngFor= "let item of data | keyvalue" >
        <td>{{item.key}} : {{item.value}}</td>
</table>

Currently, I am using *ngFor to iterate through the array, but want to exclude certain keys/values from being displayed

For instance, I wish to show key2 and value2 but not key1 and value1

[Key1 : value1], [Key2 :value2]

Any suggestions on how to achieve this would be highly appreciated

Answer №1

From my point of view, there are at least two ways to approach this situation. The first option is to filter the observable data:

this.service.getData().pipe(
    filter(o => {
        return // your condition here
    })
).subscribe(result=>{

The second alternative is to develop a custom pipe. By creating a pipe that extends the keyvalue pipe and filters the data according to your requirements, you can achieve the desired outcome. Various tutorials are available that provide detailed instructions on how to create custom pipes.

Answer №2

I believe utilizing the Angular Slice Pipe would be beneficial for this situation.

<table>
    <tr *ngFor="let item of data | keyvalue | slice: 1">
        <td>{{item.key}} : {{item.value}}</td>
</table>

I hope this solution proves to be helpful. Thank you!

[1]: https://angular.io/api/common/SlicePipe

Answer №3

One important tip: always assign types to your variables. This helps you keep track of the data you're working with and makes it clearer for others to understand your goals.

My recommendation is to move this logic into a service for reusability. Additionally, consider using a reactive approach to avoid manual unsubscribing from requests. The code assumes that the API response is an array, not an object.

apiservice.service.ts

...
export class ApiserviceService {
  data$ = this._http.get('APIURL').pipe(
    map(data => data.filter(item => item.key !== 'Key1'))
  );

constructor(private _http:HttpClient) { }
...

data.component.ts

...
public data$ = this.service.data$;
...

data.component.html

<table>
    <tr *ngFor= "let item of data$ | async" >
        <td>{{item.key}}</td>...
</table>

In this case, I suggest avoiding pipes as they should be more generic and your filtering logic appears too specific for a pipe implementation.

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

Create a d.ts file in JavaScript that includes a default function and a named export

While working on writing a d.ts file for worker-farm (https://github.com/rvagg/node-worker-farm), I encountered an issue. The way worker-farm handles module.exports is as follows: module.exports = farm module.exports.end = end When trying to replica ...

Exploring the Method of Utilizing JSON Attribute in typeScript

How to access JSON attributes in TypeScript while working on an Angular Project? I'm currently in the process of building an Angular project and I need to know how to access JSON attributes within TypeScript. test:string; response:any; w ...

Is Angular 2 built on Shadow DOM or Virtual DOM architecture?

When it comes to updating the DOM in Angular 2, does it utilize Shadow DOM or Virtual DOM? And did Angular 1 have a similar concept? ...

Is it possible to automatically switch to a different route in a Next.js server component after a certain period of time?

Is it possible to achieve a similar function in an async server component: displaying the ui, waiting 3 seconds, and then redirecting to another route? In a client component, you can accomplish this using: useEffect(() => { function delay(ms: number) ...

When ts-loader is used to import .json files, the declaration files are outputted into a separate

I've encountered a peculiar issue with my ts-loader. When I import a *.json file from node_modules, the declaration files are being generated in a subfolder within dist/ instead of directly in the dist/ folder as expected. Here is the structure of my ...

Unable to simulate the navigator.language

I'm currently in the process of writing unit tests for some of my shared utility functions. As someone who is relatively new to unit testing, I am encountering difficulties when trying to mock certain global objects. Specifically, I am struggling to f ...

The functionality of ngModel is not functioning properly on a modal page within Ionic version 6

Currently I am working on an Ionic/Angular application and I have encountered a situation where I am attempting to utilize ngModel. Essentially, I am trying to implement the following functionality within my app: <ion-list> <ion-item> <ion ...

issue connecting asynchronous pipe inside a custom directive input

There seems to be a bit of an issue! I have a custom directive that adds a hidden attribute based on input provided. import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core'; @Directive({ selector: '[ticketingPrim ...

Struggling to fetch information with Angular HttpClient from an API that sends back a JSON response with an array

As a beginner in Ionic and Angular, I am attempting to call an API and then showcase the team names within the template of my project. Despite following numerous tutorials and videos, I seem to be stuck as the JSON response returns an object with results f ...

Having difficulty implementing Angular 4 redirection for transitioning from old hash URLs to new non-hash URLs

In our single page application, we originally had a simple tab structure where each tab click led to a corresponding #url. Examples: , After transitioning to Angular 4, the urls no longer contain hash symbols. They now look like this: , I have added the ...

Prevent the display of list elements upon clicking by utilizing Angular's Observable and async features

My search bar allows users to enter characters, and through Angular Observable with HTTP GET, they receive suggestions for similar keywords. When a user clicks on a suggestion, it populates the search form with that keyword. The issue is that even after s ...

Is there a way to add an event listener to dynamically generated HTML using the v-html directive?

I have a string variable named log.htmlContent that contains some HTML content. This variable is passed into a div to be displayed using v-html. The particular div will only be displayed if log.htmlContent includes an img tag (http: will only be present in ...

What is the best method for confirming that a string is not undefined, null, or an empty string in an Angular template?

Is there an efficient method to verify whether a string is not undefined, null, or '' in an angular template? If the value is valid, then show this section. <div class="flex-row date-area" *ngIf="startDate !== undefined && startDate ...

Securing APIs in Ionic 3 with REST authentication

I am currently in the process of creating a login page for an Ionic 3 app. The code snippet below showcases what I have implemented so far in home.ts: import { Component } from '@angular/core'; import { NavController } from 'ionic-angular&a ...

Is there a way to create a tuple property that can be called like a

I have a specific function in my code: function test(cb: Function | number) { let item = { height: 0} if(typeof cb === 'number') { item.height = cb; } if(typeof cb === 'object') { item.height = cb(); } } This function ...

Is it possible to conditionally trigger useLazyQuery in RTK Query?

Is it possible to obtain trigger from useLazyQuery conditionally? const [trigger] = props.useLazySearchQuery(); My objective is to retrieve trigger only when useLazySearchQuery is provided in the props. One way I can achieve this is by using const [ ...

Angular route fails to load the HTML file

In the process of developing a route within an Angular application, I have successfully implemented 3 routes. However, one particular route is giving me trouble. I have three folders that need to redirect HTML based on the option chosen. In Angular, I cre ...

Angular's HttpClient enables you to easily map an object to an array of properties

I have a scenario where I am calling an API that returns a JSON Object, and my task is to map this object to an array. Despite having the following code, I am not receiving any response or error after making the API call. export class Features { MenuId ...

Receiving contextual information from Microsoft Teams within an Angular application integrated as a tab

I am currently integrating an Angular website into a Microsoft Teams tab. In order to perform certain computations, I need to retrieve the Team ID. To achieve this, I have recently added npm install --save @microsoft/teams-js. Below is the code snippet th ...

PHP tips: Storing array variables within another array efficiently

I am creating mathematical questions such as 3 * 5 = ? and ? * 5 = 15. To achieve this, I have initialized two arrays: $arrayTotalQuestions containing numbers 1 to 10 and $arrayAnswers consisting of 5, 10, 15, 20, 25, 30, 35, 40, 45, 50. These arrays will ...