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

I seem to be failing at properly executing Promises... What crucial element am I overlooking in this process?

Within my project, there exists a file named token.ts which contains a function that exports functionality: import * as jwt from 'jsonwebtoken'; import { db, dbUserLevel } from '../util/db'; export function genToken(username, passwor ...

Switch between classes when hovering over / exiting ngFor elements

Displayed below is an element created using ngFor <span *ngFor="let picture of pictures; let i = index"> <a target="_blank" href="{{picture.image}}" class="thumbnail-display image-overlay"> <span class="overlay-icon hide"> ...

Angular 2, 4, or 5 - the powerful choices for web

As I make the shift from AngularJS to Angular, I am seeking advice from fellow developers on which version of Angular to focus on learning. I have been utilizing AngularJS 1.3.7, but realize that it is outdated with significant advancements in Angular 2 a ...

I am currently attempting to deploy my React application using Vercel. I followed all the necessary steps in my terminal, but unfortunately encountered an error at the end: "Error: Command 'npm install' exited with 1"

Here are the problem details: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5022353133247d2333223920242310657e607e61">[email ...

The data type 'Observable<any>' cannot be assigned to the type 'StoresSummaryResults'. The property 'Data' is not present in the 'Observable<any>' type

As a newcomer to using the Observable with Angular 2, I am facing an issue where my structure is not receiving the results despite being able to validate the response from my REST API. Below is the data class in Typescript that I have: import { RESTResul ...

How to easily upload zip files in Angular 8

Currently, I am working on integrating zip file upload feature into my Angular 8 application. There are 3 specific requirements that need to be met: 1. Only allow uploading of zip files; display an error message for other file types 2. Restrict the file s ...

Encountered an error while attempting to upgrade to the latest @angular/cli version 1.0.0: Unexpected symbol "<" found in JSON at the beginning of the file

When I was using angular-cli 1.0.0 beta 23, my service was able to fetch a local JSON file for testing without any issues. However, after upgrading to angular/cli 1.0.0, I encountered the following problem: GET http://localhost:4200/json/inputInventory/ ...

Using the ternary operator will always result in a TRUE outcome

Having trouble with a ternary operator expression. AssociatedItemType.ExRatedTag ? session?.data.reloadRow(ids) : this.reloadItemRows(this.prepareItemsIdentities(ids)!), The AssociatedItemType is an enum. I've noticed that const ? 1 : 2 always retur ...

Issue with the Material UI theme module enhancement feature not functioning as expected

I've been researching the MUI documentation, blogs, and various posts on Stackoverflow, but despite my efforts, I can't seem to get my vscode intellisense/typescript to recognize the changes I've made. These are fairly straightforward modif ...

The in-memory-web-api is failing to respond to queries when using Chrome

I've been experiencing an issue with my in-memory database setup. Even though I have registered everything correctly, I am not receiving any data back. There are no errors or 404 responses; it seems like the app is intercepting the request and returni ...

Troubles in transitioning a local project from Angular 2 to Angular 4 using Angular-cli

I have been working on updating an angular-cli/angular 2 project to Angular 4. I successfully updated the package.json file with all the necessary Angular 4 modules, but encountered an issue when running the application. Upon running the app, I received th ...

Issue with updating BehaviorSubject not being reflected when called from my service component has been identified

In my HomeComponent, I am currently using *ngIf to switch between 3 components. The focus right now is on the relationship between two of them - the ProductListComponent and the ProductDetailComponent. Inside the ProductListComponent, there is a ProductLis ...

What is the best way to access data from a local JSON file in Gatsby when using TypeScript and GraphQL?

I'm updating my former gatsby site using TypeScript. I encountered an issue while trying to retrieve data from a local JSON file: There appears to be an error in your GraphQL query: Cannot find field "allNavigationLinksJson" on type "Q ...

Importing Json in Angular 8: A detailed guide

I recently came across information that you can now directly import JSON in TypeScript 2.9 and made changes to my tsconfig.json file accordingly: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", " ...

Error Message: ES5 mandates the use of 'new' with Constructor Map

Below is the code snippet: export class ExtendedMap<T, U> extends Map { constructor() { super(); } toggle(key: T, value: U) { if (this.has(key)) { super.delete(key); ...

Nativescript Image-picker is encountering difficulties locating files in external storage

I have been using nativescript-imagepicker from the related website and followed all the instructions in the documentation and sample codes. I even set the permission code in AndroidManifest.xml for API 29 and higher. However, I encountered an error after ...

Angular issue: Readonly or disabled input fields not submitting data

Struggling with creating a form in Angular 2 to submit dynamically generated values from a service. The goal is to calculate the equivalent amount of bitcoin for X chilean pesos using Angular's http module to fetch the price. However, facing an issue ...

Troubles with Conditional Application of CSS Styles to a Twitter-Bootstrap Table

I am facing an issue with highlighting a row in a table when a barcode is entered. Despite following similar scenarios and checking my code, the CSS doesn't seem to be applied. Can anyone help me figure out what I'm missing or how I can fix this? ...

Error: The function User.findOne is not recognized

Currently, I am in the process of developing a Node.js API and aiming to implement JWT for login functionality. I have successfully set up the model and route, and while testing with Postman using the POST method, an error occurs upon sending the request. ...

Having trouble customizing the toolbar on ngx-quill? Quill seems to be having trouble importing modules

UPDATE: I jumped ship when I discovered that PrimeNg had a quill implementation, and since I was already using PrimeNg, I switched over. Initially had some issues, but upgrading to angular 7 and ngrx 7 beta resolved them. https://www.primefaces.org/primeng ...