Using Angular material to display a list of items inside a <mat-cell> element for searching

Can I use *ngFor inside a <mat-cell> in Angular?

I want to add a new column in my Material table and keep it hidden, using it only for filtering purposes...

My current table setup looks like this:

<ng-container matColumnDef="email">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Email </mat-header-cell>
    <mat-cell *matCellDef="let user"> {{ user.email }} </mat-cell>
  </ng-container>
  <ng-container matColumnDef="phone">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Phone </mat-header-cell>
    <mat-cell *matCellDef="let user"> {{ user.phone }} </mat-cell>
  </ng-container>

Now, I need to include a row displaying {{ user.book.name}}, but my attempt at using *ngFor is not functioning as expected. Here's what I tried:

<ng-container *ngFor="let book of user.book" [matColumnDef]="book">
   <th mat-header-cell *matHeaderCellDef mat-sort-header> {{ book}} </th>
   <td mat-cell *matCellDef="let book"> {{ book.name }} </td>
</ng-container>

This solution has caused some issues throughout my app...

You can see an example on StackBlitz. The "OBJECT" mentioned in the code represents the placeholder where I am trying to display the names of books.

Answer №1

To accomplish the task at hand, we needed to perform two actions: - create a new array where the existing array of books is stored as a string - conceal this particular column in the HTML (you can remove the display:none style attribute to test)

Here is the relevant HTML snippet:

<!-- Books Column -->
  <ng-container matColumnDef="books" >
    <th mat-header-cell *matHeaderCellDef style='display:none'> Books </th>
    <td mat-cell *matCellDef="let element" style='display:none'> {{ element.books }}  </td>
  </ng-container>

And here is the pertinent TS portion:

import {Component} from '@angular/core';
import {MatTableDataSource} from '@angular/material/table';

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
  books: any[];
}

const ELEMENT_DATA: PeriodicElement[] = [
  // sample data for elements with their respective book lists
];

/**
 * @title Table with filtering
 */
@Component({
  // component details
})
export class TableFilteringExample {
  // declarations and initializations

  constructor(){
    // logic to store book arrays as strings in a new variable
  }

  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol', 'books'];
  dataSource = new MatTableDataSource(this.newVar);

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

For a comprehensive demonstration, refer to this functional StackBlitz example

Answer №2

If you have an array that you want to iterate through and format, you can achieve this using *ngFor:

<td mat-cell *matCellDef="let element">
   <span *ngFor="let person of element.books;"> 
     {{ person?.name }}
  </span>
</td>

For a demonstration, please refer to this StackBlitz example

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

What is the best way to ensure the search box remains fixed in the top navigation bar while maintaining a fluid and responsive design?

I've been struggling as a novice programmer, and even with the help of more experienced programmers, we haven't been able to figure it out. I'm trying to integrate a search box into the top navigation that adjusts responsively to different ...

What is the best way to extract the value from a resolved Promise?

Currently, I am attempting to read a file uploaded by the user and convert it into a String using two functions. The first function is handleFileInput: handleFileInput(event){ setTimeOut(async()=>{ let abcd= await this.convertFileToString(this.fi ...

Configuring ordered imports in TSLint

Need help with configuring my TSLint rule ordered-imports. I want the import order to be like this: // React import React from 'react'; import { View } from 'react-native'; // Libs import * as _ from 'lodash'; import * as mo ...

A step-by-step guide to implementing Auth0 login within an iframe

I recently developed a basic Angular app that features a Login with Auth0 button. The functionality works perfectly when accessed directly through the browser, allowing users to log in successfully. My ultimate goal is to embed this app into another webpag ...

Encountered difficulties when trying to incorporate SCSS into my rollup build

Desired Outcome I aim to develop a small library for personal use, focusing on separating code into library (product) and application (project) code. All my source code resides in the /src folder, consisting of React, TypeScript, and SCSS code. I would l ...

Validating SASS based on class name

Hi there, I am fairly new to SASS and do not consider myself a programming expert. I have ten aside elements that each need different background colors depending on their class name. Even after going through the SASS documentation, I am still unable to f ...

VS Code warning about unused CSS selectors in SvelteKit

Is there a way to get rid of the Unused CSS selector warning in VS Code? I keep getting this warning in all files where I use <style lang="scss">. While I'm aware that I don't use the .btn class in some components, I still want it ...

Getting event properties in a React component using the rest operator: A comprehensive guide

Can someone please assist me? I am new to TypeScript and struggling with how to use event props in my component. I have defined two props and need all my events as rest props. I encountered an error when trying to use my component with onClick event. The ...

Guide for displaying information as a grid or table format using Angular 4

I am tasked with handling data from an external microservice that is not always in a standard format. The data is dynamic and can include table data, along with metadata information above the grid. My challenge is to render or identify the table data, disp ...

Is there a way to adjust the spacing between cards in Bootstrap?

I am attempting to replicate the layout shown in the attached picture. How can I adjust this property? Expected output: I would like the elements to be closer together and centered on the page, but I am struggling to achieve this. I have tried adjusting ...

section featuring a striking visual, user input form, and descriptive content

I want to create a layout with a background image in a div, a signup form on the right side, and a div containing h1 tags on the left side. Here is the HTML code: <html> <title> GoToMy PC </title> <head> <link rel="stylesheet" ...

Change the CSS menu item to directly load the website instead of using javascript to replace a placeholder

I have a CSS navigation menu, but I'm facing an issue. When I click on a link in the menu, like Google for example, it only changes the name of the placeholder and doesn't actually load the page. Any suggestions on how to fix this? Thank you for ...

Is it possible to incorporate an element using absolute positioning using jQuery or Javascript?

When trying to add a new element on the screen, I am facing an issue with the absolute positioning not working properly. Sample Code in Javascript function drawElement(e,name){ $("#canvas").append("<div id='" + name + "' class='e ...

The type 'NextApiRequest' lacks the following attributes compared to type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'

An error has been identified in the code for a Next.js project below. The error message reads: Argument of type 'NextApiRequest' is not assignable to parameter of type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any ...

The browser fails to implement styling prior to a demanding workload

Is it possible to refresh a section of my webpage that contains numerous DOM elements? My ideal approach would be to hide the section using visibility: hidden;, then redraw it, and finally set visibility back to visible;. However, I've encountered an ...

Update ng-Bootstrap ToDate field by removing the date when selecting a fromDate

Is there a way to clear the date from the toDate input field while selecting a date from the fromDate input field in ng-bootstrap? <form class="row row-cols-sm-auto" *ngIf="showDateRangeImp"> <div class="col-12" ...

I want my Angular 2 application to redirect to the appropriate page when a user who is logged out attempts to access a page that requires them to be logged in

When a user is logged out in Angular 2 router and they try to navigate to a page that requires them to be logged in, I need the app.ts file to redirect them. I am utilizing typescript along with angular 2. Oddly enough, the redirection works for certain ...

What is the process for incorporating JavaScript files into an Angular project?

I have a template that works perfectly fine on Visual Studio. However, when I try to use it on my Angular project, I encounter an issue with the JavaScript code. I have filled the app.component.html file with the corresponding HTML code and imported the ...

Guide on setting up and configuring the seeder in MikroORM

Hey there, I recently tried to execute seeders in MikroORM and encountered a problem. I followed all the steps outlined here: . In the MikroORM route folder (alongside mikro-orm.config.ts), I created a seeders directory. I updated mikro-orm.ts with the fo ...

The vertical-rl writing mode fails to function properly when the website is viewed within the Facebook app

I am facing an issue with a vertical button on my website. It works fine in browsers, but when the webpage is shared on Facebook and opened within the Facebook app, the button's alignment gets distorted. How can I resolve this problem? <div class= ...