Ways to populate missing cells with a default hyphen symbol

Looking for a way to default empty cells in my primeng datatable to '-'.

Consider the following data:

[
{
 'column': null
},
{
 'column': {
  'name': 'A'
 }
},
{
 'column': {
  'name': 'B'
 }
},
{
 'column': null
}
]

The configuration of my primeng column is as follows:

{  
 field: 'column.name',
 header: 'Name',
 sortable: true
}

However, the current setup does not work when "column" may or may not have the property "name". It sets all fields in this column to '-', regardless of the presence of "name".

 <p-column [field]="col.field" [header]="col.header" [sortable]="col.sortable">
     <template let-col let-data="rowData" pTemplate="body">
         {{data[col.field] ? data[col.field] : "-"}}
     </template>
 </p-column>

If you have any ideas on how to solve this issue, please share!

Answer №1

I utilized a custom pipe in Angular2 for this solution.

Here's how you can implement it:

  1. Begin by creating a custom pipe, learn more about the process here:

import {
  Pipe,
  PipeTransform
} from '@angular/core';
/*
 * If piped value is falsy, default to given default value or - (hyphen)
 * Takes an defaultValue argument that defaults to - (hyphen).
 * Usage:
 *   value | defaultTo:'N/A'
 * Example:
 *   {{ orders.attributes?.first_name | defaultTo}}
 *   formats to: -
 *
 * Written by Henrik Peinar 06/04/2017
 */
@Pipe({
  name: 'defaultTo'
})
export class DefaultToPipe implements PipeTransform {
  public transform(value: string, defaultValue?: string): string {
    return (value) ? value : (defaultValue !== undefined ? defaultValue : '-');
  }
}

  1. Ensure your custom pipe is declared in your app so it can be used:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';
// ... other imports ...
import { DefaultToPipe } from './default-to.pipe';

@NgModule({
  imports:      [ BrowserModule, HttpModule],
  declarations: [ AppComponent, DefaultToPipe ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

  1. Implement your custom pipe within your templates as shown below:

<tr *ngFor="let order of orderList">
      <td>{{order.order_number}}</td>
      <td>{{order.phone | defaultTo:'No phone'}}</td>
      <td>{{order.shipping_address?.first_name | defaultTo}}</td>
      <td>{{order.shipping_address?.last_name  | defaultTo}}</td>
</tr>

A fully functional snippet was not provided due to Angular2 not being recognized as a valid dependency in the snippet provider.

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

The execution of the server.js file in the dist folder does not display any

Currently, I am working on an Angular Universal app. By using the command 'npm run start', I can successfully execute 'ng serve' and the live development server becomes active. However, when attempting to run 'node dist/server.js ...

Are there any @types available for browser extension objects that are interoperable?

I am in the process of developing a browser extension that would work seamlessly on Edge, Chrome, and Firefox by utilizing Typescript. After coming across an article discussing interoperable browser extensions, I stumbled upon a code snippet: window.brow ...

Customize styles for a specific React component in a Typescript project using MaterialUI and JSS

I'm currently exploring how to customize the CSS, formatting, and theme for a specific React component in a Typescript/React/MaterialUI/JSS project. The code snippet below is an example of what I've tried so far, but it seems like the {classes.gr ...

What causes the difference in inference for unspecified generics between a simple function call and a null-coalescing operator in TypeScript?

What causes the different types of a and b in the given code snippet? function empty<T>() { return [] as T[] } const defEmpty = empty() function test1(abc: number[]|null) { const a = abc ?? defEmpty const b = abc ?? empty() } Upon testing on t ...

Utilizing Google Analytics 4 in a React TypeScript Environment

Currently, there are two options available: Universal Analytics and Google Analytics 4. The reasons why I lean towards using Google Analytics 4: Universal Analytics is set to be retired on July 1, 2023, so it makes sense to start fresh with Google Analyt ...

Deactivating a form field depending on a selected radio button in Angular 2

If I have two radio buttons, with a click function called localClick for the first button to give value 1 and the second button to give value 2. <div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"&g ...

CORS policy causing Socket.io communication issues in a Node.js and Angular app

I have a node.js server running with express and socket.io. When I try to communicate with a simple JavaScript client, everything works fine. However, when I attempt to establish communication with an Angular app (using ngx-socket-io), I encounter the foll ...

Guide on inserting Angular 2 attributes within a variable in an Angular 2 TypeScript class

I have a variable 'content' in the 'findCharityHome.ts' typescript class structured like this. let content = ` <b>`+header+`</b> <button style='background-color:#428bca;color:white; ...

What is the correct way to define an abstract method within a class to ensure that an IDE detects and notifies if the abstract method is not implemented

Is there a way to properly define an abstract method in an abstract class and have the IDE notify us if we forget to implement it? I attempted the following approach, but it did not work: export abstract class MyAbstractClass { /** * @abstract ...

Tips for sorting the mat table dataSource by inputting two columns and selecting the search button

I am currently displaying mat table data with columns for Role, Status, Email ID, and Name. Above the table, there is a search area where users can enter values for Role and Status and then click the Search button. If the entered values match exactly for ...

What steps should I take to resolve the ChunkLoadError related to signalr?

Recently, I encountered an issue while running my nx site locally. It seems that any federated app using signalR is now throwing a ChunkLoadError. I attempted various solutions such as changing the version of signalR, reloading the page, clearing cache, a ...

Having trouble with window.scrollTo(0, 0) and scrollTop = 0 when navigating routes in Angular 2?

This issue has been causing me a lot of frustration. I have completed my application except for one final task. I have been attempting to auto-scroll to the top of the page when there is a change in the router. Despite trying 10 different solutions found o ...

Error encountered while upgrading to Angular 5: splitHash issue

Currently in the process of transitioning from Angular 4.x to 5.x, I have encountered the following error: main.81bcdf404dc22078865d.bundle.js:1 Uncaught TypeError: i.splitHash is not a function at Object.t.parseUrl (main.81bcdf404dc22078865d.bundle.js:1) ...

Tips for arranging columns and rows in a mat-dialog box

In my Angular project, I am working on a mat dialog box and trying to achieve a layout with 1 row at the top and 3 rows at the bottom, similar to the image below. However, I am facing issues in making it work properly. Additionally, I want to hide the hori ...

Retrieve the array from within the string

Any suggestions on how I can extract the array from this string? The current string is: "['Biller.Customer.Data@Taxonomy', 'Product.Platform and Enterprise Services Data.Data@Taxonomy']" I need to extract it to look like thi ...

Experiencing difficulty in retrieving data streams in Angular 5 when using the pptxGenjs library

I am working on incorporating images into a PowerPoint file using pptxGenjs in Angular5. While I have successfully retrieved the file with content, my goal is to extract the data from the PowerPoint file in base64 or a similar output format. However, all ...

Where should messages be pushed within the Angular constructor using Observables and Subjects?

I have created a MessagesService which allows me to send and receive messages: export class MessagesService { constructor() { } private subject = new Subject<any>(); sendMessage(message: string): void { this.subject.next({ text: message ...

Retrieve the value within the finalize pipe from a test execution

I have a component with the following code: isLoading: boolean; users: User[]; test: number = 1; ngOnInit() { this.isLoading = true; this.userService.getUsers() .pipe( finalize(() => { // Disable loading when complete ...

Dealing with tag conflicts in Angular with ngx-translate

Within my student.component.ts file, I am constructing table output using the following code: var html = ...... html +='<li><a class="fanta" data-element-id="' + student.Id + '">Set as Draft</a></li& ...

Issues arise when trying to implement Angular class and it does

I'm currently facing some challenges using classes in Angular to simplify my coding process. So far, I haven't been able to get it to work properly. Below is the code snippet I'm working with and the error message that pops up: import { Wiz ...