Displaying only the matched column in an Angular table

I am attempting to display only the matched columns in a table, but I am unsure of how to achieve this. If anyone has any ideas or solutions, please help me out.

app.component.ts:

 columnsOnly = ['name', 'id', 'rank']; 
  items = [
    { name: 'jean', surname: 'kruger', id: 1, place: 'ckh', rank: null },
    { name: 'bobby2', surname: 'marais2', id: 2, place: 'ckh', rank: null },
    { name: 'jean3', surname: 'kruger3', id: 3, place: 'ckh', rank: null },
    { name: 'bobby4', surname: 'marais4', id: 4, place: 'ckh', rank: null },
    { name: 'jean5', surname: 'kruger5', id: 5, place: 'ckh', rank: null },
    { name: 'bobby6', surname: 'marais6', id: 6, place: 'ckh', rank: null }
  ];

app.component.html:

 <table>
  <thead>
    <tr>
      <th *ngFor="let head of items[0] | keys: index as i">

        <span *ngIf="head == columnsOnly[i]">
        {{head}} </span>

      </th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of items">
      <td *ngFor="let list of item | keys">{{item[list]}}</td>
    </tr>
  </tbody>
</table>

Demo: https://stackblitz.com/edit/angular-71f59e?file=app%2Fapp.component.html

Answer №1

Why aren't you iterating over the columnsOnly array?

<tr>
  <th *ngFor="let column of columnsOnly">
    <span>{{column}} </span>
  </th>
</tr>

<tr *ngFor="let item of items">
  <td *ngFor="let column of columnsOnly">{{item[column]}}</td>
</tr>

Update: It would be better if our columns were an array of objects with both "label" and "field" properties. For example, if we had an array like this:

columnsOnly = [
    {label:'First Name',field:'firstName'},
    {label:'Sur Name',field:'surname'}, 
    {label:'ID Type',field:'idType'},
    {label:'Near Place',field:'nearPlace'}
];

We could update the loop as follows:

<th *ngFor="let column of columnsOnly">
    <!-- Use column.label here -->
    <span>{{column.label}} </span>
  </th>

  <tr *ngFor="let item of items">
    <!-- Use column.field here -->
     <td *ngFor="let column of columnsOnly">{{item[column.field]}}</td>
  </tr>

Update 2: Another approach is to define all columns and create a "map" using them:

columns=['First Name','ID Type']
columnsOnly=this.columns
                 .map(x=>this.columnsAll.find(c=>c.label==x))

(Assuming we have defined "columnsAll" with both "label" and "field")

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

Angular service is continuously throwing the error message "NullInjectorError: No provider for anotherService"

I recently built a basic Angular service and encountered an issue. @Injectable() export class someHandler { constructor( public anotherService: anotherService, ) {} ... The problem arises when I try to use this service in a component, as ...

Tips for embedding a hyperlink in your HTML website

While I've mastered adding images to my HTML website, there's one thing that still eludes me despite scouring numerous online resources. I recently created a small animation using JavaScript on a different IDE, and I have the link to my output: ...

Error when redirecting in Express due to invalid integer input syntax

After executing a PUT query in Postgres through Express, I encountered the following error message: Error: invalid input syntax for integer: "all-calls" This issue seems to be related to the line of code within the router.put function that says response. ...

Double-click required to toggle button

Here is the code snippet for controlling an LED using a web page. The script, linked to Python, effectively controls the LED. However, there is an issue where the button toggles to the right side (ON position) only after a double click. Upon first click ...

I'm looking for a client-side JavaScript library that can queue AJAX requests and also support storage. Can anyone recommend

Currently seeking a JavaScript client-side library that can manage a queue of Ajax or WebSocket requests with the following features: Request transmission when the user is online and the server is operational Request storage when the user is offline or t ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

Error encountered: Unable to access the 'Lastname' property as it is undefined

Even though the console displays the value of $("#surname").val(), I am still encountering an error. Could it be that the script is executing before the form is dynamically built? $(function () { $("#addEmployeForm").submit(function (event) { ...

Is it possible to insert clickable links within the content of a Twilio text message?

Currently, I am utilizing Twilio and Express to send programmable SMSs to the users of my web application. I'm curious if it's possible to include hyperlinks within the body of these text messages. Is there a method to achieve this? I have attem ...

From organizing nested arrays in jSon to visualizing data with D3js

I am completely new to working with d3 and JSON. I have a piece of data from JSON that I am attempting to extract, and I'm wondering if I am headed in the right direction. My goal is to display a rectangle graph for each server within different statu ...

"Encountered an issue with combining multiple meshes that share the same geometry but have

I wrote a loop that generates multiple Mesh objects with various geometries, where each mesh corresponds to a specific texture: var geoCube = new THREE.CubeGeometry(voxelSize, voxelSize, voxelSize); var geometry = new THREE.Geometry(); for( var i = 0; i ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

In AngularJS, the decimal point is represented by a comma

Several countries use the point as a comma for numbers, and the comma as a decimal separator. This includes Europe (excluding UK and Ireland), South America, Russia, and French West Africa. Find more information on Wikipedia How can we determine if a user ...

Recommendations for Configuring VPS for Angular2 and .Net Application

My team and I are currently in the process of developing an application that combines Angular2 for the front-end and Web API ASP.NET for the back-end. We are currently at the stage of configuring a VPS for this application but unfortunately, we lack the ...

Substitute dynamic Angular expressions with fixed values within a string

Inside my angular controller, I am defining a stringTemplate containing expressions like "{{data.a}} - {{data.b}}". Along with that, I have an object named data with values {a: "example1", b: "example2"}. My goal is to find a way to replace the dynamic ex ...

"Step-by-step guide on adding and deleting a div element with a double click

$(".sd").dblclick(function() { $(this).parent().remove(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table width="750" border="0" cellpadding="0" cellspacing="0"> <tr> <t ...

Struggling with Angular CLI installation on Mac?

I've been trying to install Angular on my Mac's global directory, but I haven't been successful after multiple attempts. I've tested the following commands: npm install -g @angular/cli npm install -g @angular/cli@latest How to upgrad ...

Why is a dispatch call in React-Redux being executed before another?

My Pokedex is functioning properly, but I have encountered an issue with React-Redux Dev Tools: https://i.sstatic.net/F0Ifh.png The function "getPokemonsInfo" is being called before "getPokemonsUrls", however, "getPokemonsInfo" should only be triggered w ...

Creating a seamless integration between Angular 2's auth guard and observables to enhance application security

I'm having trouble setting up an auth guard for one of my routes because I am unsure how to implement it with an observable. I am using ngrx/store to store my token. In the guard, I retrieve it using this.store.select('auth'), which returns ...

What should be the return type of a Jest test when written in a Typescript function?

When encapsulating a Jest test in a function with TypeScript, what is the expected return type? Thank you. const bar:ExpectedReturnType = () => test('this is another test', expect(false).toBeFalsy()); ...

What is the best way to choose the initial element in every group using jQuery?

If we have the following HTML input: <p>A</p> <p>B</p> <p>C</p> <div>D</div> <p>E</p> <p>F</p> <p>G</p> We can select B, C, F and G using the following code: $('p + ...