Verify whether the data within the array is a string or a date, and convert it as needed

I am trying to determine the data type (string or date) of the values coming from a loop in a p-table

There is a key called newValue which can have two possible values: newValue: "Percentage" or

newValue: "2021-03-25T15:55:42.136Z"

If the value is a date, I want to display it as "3/25/21, 9:25 PM" otherwise just show the string "Percentage"

 <td style="width: 10%;">
        {{rowData?.histories.newValue ? getDateorStringValue(rowData?.histories.newValue) : 'N/A'}}
      </td>
    getDateorStringValue(...) 

This function is what I'm using, any suggestions on how to achieve this?

Answer №1

One option is to create a simple pipe for the comparison.

date-or-string.pipe.ts

import { Inject, LOCALE_ID, Pipe, PipeTransform } from "@angular/core";
import { DatePipe } from "@angular/common";

export const checkIfDate = (date: string) => {
  return !!Date.parse(date);
};

@Pipe({
  name: "dateOrString"
})
export class DateOrStringPipe extends DatePipe implements PipeTransform {
  constructor(@Inject(LOCALE_ID) locale: string) {
    super(locale);
  }

  transform(
    value: any,
    format?: string,
    timezone?: string,
    locale?: string
  ): any {
    return checkIfDate(value)
      ? super.transform(value, format, timezone, locale)
      : value;
  }
}

Usage

<td style="width: 10%;">
  {{ rowData.histories.newValue | dateOrString:'M/dd/yy, h:mm a'}}
</td>

It is important to note that using Date.parse() for comparison may only work with strings. There are more effective ways to compare, as explained here.

See a working example here: Stackblitz

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

Error: Unable to access the property 'firstname' of an undefined variable

After creating the component and HTML file, I defined a model and combo box values within the component. However, when attempting to bind these model values to a text box and combo box in the HTML file, the combo box did not display any values and the mode ...

The PrimeNg datatable fails to update and display the latest data

Using Angular version 2.4.8 along with PrimeNg version 1.1.4 I am working on a page that consists of two components: A Dropzone component for uploading files A p-datatable component to display the uploaded files The Dropzone component is configured to ...

Angular TypeScript Directive Link function not being executed

I've been working on implementing a Role-Based-Access-Control system in my application. The allowed resources are loaded from the server after login, and I was able to verify this using raw JavaScript code. angular.module('app').directive(& ...

Generating lazy-loaded Angular modules using AOT in Ionic-app-scripts with webpack

We are currently working on developing a unified angular (4) and ionic (3) application using the same codebase with the help of ionic-app-scripts for building. However, we have encountered an issue during the production build specifically related to angula ...

Why is the text returned by the Angular Response body missing the JSON brackets? Strange, isn't it

As a newcomer to Angular 2, I should mention that some information is internal and will be replaced with placeholders when needed. My current task involves making a simple post request and retrieving the contents of the request body. Below is my existing ...

Learn how to incorporate internationalization (i18n) in Angular 4 with this detailed example

Would appreciate guidance on implementing i18n in Angular 4 as I am new to this framework. The project is generated using Angular CLI and I want to incorporate i18n into it. Any assistance on how to achieve this would be highly appreciated. Many thanks in ...

Angular 7's StyleUrl that Adapts to Your Needs

Is there a better way to dynamically load styles in Angular 7? I have tried the example below but it's not working in version 7 of Angular. This code worked fine in earlier versions before Angular 7. Can someone offer some help or advice please? Thank ...

Make sure the subset interface is selected from the interface / Choose PickDeep<>?

I am searching for a solution using the following interface: interface Person { age: number, name: string, hometown?: { city: string, zip: number } } type SubPerson = EnsureSubInterface<Person, { name: string }> an example that w ...

transferring information between two sibling elements in Angular 7

My goal is to display the username of the logged-in user on the home page. I have a LoginComponent, HomeComponent, and I am using a service called DataService.ts for data transfer. The data seems to be reaching DataService.ts but it's not getting to t ...

Creating a reusable API call function with the fetch method

I need to create a general function that can handle all of my API calls from anywhere in my application Currently, I am using React version 16.8.6 and fetch for making API requests Here is what I have come up with so far: Helper.js export function ApiH ...

Learn how to effectively utilize the onload event in Angular 2 when working with dynamically inserted image sources

How do I set specific flags once an image finishes downloading? I attempted to use the onload event on the image tag and call a function. However, the implementation below is throwing an error: Uncaught ReferenceError: imageLoaded is not defined ...

Angular's Route Guard feature is programmed to redirect users to the home page every time before they

I have been working on implementing a route guard for my website. The guard is responsible for checking the token and returning either true or false. If it returns false, it should redirect to the desired route. However, I am facing an issue where instead ...

CORS policy does not recognize the specific methods I specified in Express Gateway

I'm currently working on an Angular app and utilizing express gateway to manage my backend requests. Everything seems to be functioning correctly except for the CORS methods. I specifically want to allow only GET, PUT, and POST methods, but even witho ...

I'm having trouble grasping the issue: TypeError: Unable to access the 'subscribe' property of an undefined object

I've been working on a feature that involves fetching data from API calls. However, during testing, I encountered some errors even before setting up any actual test cases: TypeError: Cannot read property 'subscribe' of undefined at DataC ...

The proper method for specifying contextType in NexusJS when integrating with NextJS

I am currently facing a challenge while trying to integrate Prisma and Nexus into NextJS. The issue arises when I attempt to define the contextType in the GraphQL schema. Here is how I have defined the schema: export const schema = makeSchema({ types: [ ...

In Angular, there is a situation where two input fields are both referencing the same event.target

I am facing an issue where I have two input fields that are linked to the same event.target.value object, but I want them to be separate. <form class="flex-list" [formGroup]="calculation_Input" (input)="input($eve ...

Navigating images within Typescript - NextJS operations

My website fetches data from the Spoonacular API to search for ingredients, receiving responses with titles and images. I have defined the types as: export interface IProps { id: number; name: string; image: string; } Currently, my list of i ...

Ways to remove modules from an Angular build process?

Within my Angular application, there exists a multitude of modules. My goal is to omit certain modules from the Angular build. For example, I have a repository containing the entire codebase with various Angular modules such as chat, dashboard, products, ...

Error: Unable to locate module with associated type definitions when utilizing Typescript in Next.js

Currently, I am working on a next.js project that I'm attempting to integrate typescript into. The structure of my folders is organized as follows: api aggregation.ts interfaces index.ts components Component1 index.js index.module.css ...

Sort the array by the elements in a separate array

Here is a filters array with three values: serviceCode1, serviceCode2, and serviceCode3. ['serviceCode1', 'serviceCode2', 'serviceCode3'] I have another array with approximately 78 records that I want to filter based on the a ...