Leveraging CustomPipe with ngModel in Angular 7 and beyond

In my application, I am facing an issue with a date calendar picker input that is storing dates on a server and returning them onInit. The problem arises when the date is not stored or picked, as it returns 01/01/0001 numbers. My goal is to have the input either empty or display a placeholder like dd/mm/yyyy if no date has been selected or saved on the server yet. To achieve this, I created a custom pipe, but I am encountering difficulties when trying to implement it with ngModel.

The error message I receive states that the value is undefined.

Here is the relevant HTML code:

<div class="form-group">
    <label for="motDate">MOT Date</label>
    <input type="text" class="form-control" placeholder="dd-mm-yyyy" ngbDatepicker #d="ngbDatepicker" (focus)="d.open()" #motDate>
    <input type="hidden" [ngModel]="model.motDate | dateNotEmpty" (ngModelChange)="onMOTDateSelected($event)" name="motDate" />
</div>

This is the Component Typescript code:

export class VehicleFormComponent implements OnInit {  
  @ViewChild('motDate') motDatePicker;

  ngOnInit() { 
    // Displaying dates from the server in the correct format using moment
    this.motDatePicker.nativeElement.value = `moment(this.model.motDate).format('DD/MM/YYYY');`
  }

  onMOTDateSelected(e) {
    this.model.motDate = new Date(e.year.toString() + '-' + e.month.toString() + '-' + e.day.toString());
  }   
}

And here is the Custom Pipe implementation:

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
  name: 'dateNotEmpty',
  pure: false
})  
export class DateNotEmptyPipe extends DatePipe implements PipeTransform {
  transform(value: any, format: string): any {
    if (value.indexOf('0001') > -1) {
      return "";
    } else {
      return new DatePipe('en-GB').transform(value, format);
    }
  }
}

Answer №1

I believe this solution is viable.

Below are the provided codes:

//html
      <div class="form-group">
        <label for="motDate">MOT Date</label>
        <input type="text" class="form-control" placeholder="dd-mm-yyyy"
               ngbDatepicker #d="ngbDatepicker" (focus)="d.open()" #motDate>
        <input type="hidden" [ngModel]="model.motDate | dateNotEmpty" (ngModelChange)="onMOTDateSelected($event)" name="motDate" />
      </div>

//typescript
export class VehicleFormComponent implements OnInit {

  @ViewChild('motDate') motDatePicker;

    ngOnInit() { 
    // displays dates fetched from server in correct format using moment
    this.motDatePicker.nativeElement.value = `moment(this.model.motDate).format('DD/MM/YYYY');`
    }
  onMOTDateSelected(e) {
    this.model.motDate = new Date(e.year.toString() + '-' + `e.month.toString() + '-' + e.day.toString());`
 }   
}

//custom pipe
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
    name: 'dateNotEmpty',
    pure: false
})

export class DateNotEmptyPipe extends DatePipe implements PipeTransform {
  transform(value: any, format: string): any {
    console.log('Value here': value);
    if (value && value.indexOf('0001') > -1) {
      return "";
    } else {
      return new DatePipe('en-GB').transform(value, format);
    }
  }
}

Answer №2

I want to give a shoutout to Sunny for shedding some light on the issue in the comments above. I was reusing a pipe that I had used in multiple places before and hit a roadblock here. Adding an if statement after initializing the date did the trick:

Big thank you to everyone else who attempted to assist me along the way, your help is truly valued!

this.motDatePicker.nativeElement.value = moment(this.model.motDate).format('DD/MM/YYYY');
              if (this.motDatePicker.nativeElement.value.indexOf('0001') > -1) {
                this.motDatePicker.nativeElement.value = "";
              }

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

"Parent component is unable to modify the value of a child input field when ionViewWillEnter is

Scenario: Main page linked to subpage. Subpage accesses input data from main page. Upon navigation, main page updates variable in ionViewWillEnter. However, this change is not reflected in the subpage. Interactive Demo: https://stackblitz.com/ed ...

Differentiating elements from two array objects in typescript: a guide

I am facing an issue in extracting the different elements from two array objects. Here is my example: array1 = [{id: 1, a: "a", b: "b"}, {id: 2, c: "c", d: "d"}, {id: 3, e: "e", f: "f"}]; array2 = ...

error: encountering issue with Vue TypeScript Jest tests - '$store' property is undefined

I've been facing issues with my tests failing after a recent npm install. I've tried adjusting versions up and down, but haven't had any success. Interestingly, the $store isn't directly used in any of the components or tests. Despit ...

Is there a way to limit the keys of T to only number fields, where T[keyof T] is a number

I'm looking to restrict the field parameter within this function: function calculate<T>(source: T[], field: keyof T) { for(const item of source) { } } The goal is to ensure that item[field] will always be a number. Is there a way to ac ...

I ran into a SyntaxError: The usage of 'import.meta' outside of a module is not allowed - Nx Monorepo

In setting up an angular nx monorepo, two applications were created. However, when attempting to start either of them, the following error message appears: https://i.stack.imgur.com/YwYzu.png There have been suggestions on stackoverflow advising to add " ...

Streamlined method for creating forms and charts within SharePoint

When it comes to creating charts and forms on SharePoint, what is the best approach for maximizing efficiency? Using AngularJS web parts with CRUD operations. Modifying standard forms and integrating charts using JavaScript libraries and CSS. Are there ...

access denied on image links

While developing a web app with Angular5, I encountered an issue regarding retrieving image URLs from the 4chan API. Each post in my database contains an image URL, however, when I try to access it through my app, I receive a 403 forbidden error in the con ...

Creating a factory function in TypeScript to generate union types

I have developed a unique Factory type that allows me to create factory functions. export type Factory<T> = (state?: Partial<T>) => T; Within my <Avatar /> React component, I have implemented a prop with a union type to accommodate fo ...

Typescript requires that the argument passed is undefined

Typescript: 2.4.1 I am exploring the creation of a helper function to produce redux action creators. Here is what I have: interface IAction<T extends string, P = undefined> { type: T; payload: P; } function createAction<T extends strin ...

Leverage native dependencies in AWS CodeBuild for an Angular project

I am facing an issue with a build project on CodeBuild. One of the dependencies required for the project is located on the build machine itself, specifically in my own directory. The specific section in package.json that mentions this dependency is: &quo ...

When the Image Icon is clicked, the icon itself should become clickable and trigger the opening of a popup Dialogue Box for uploading a new image

When I click on the image icon, it should be clickable and a popup dialogue box will open to upload a new image. Check out this sample image for reference. Any help on this would be greatly appreciated. Thanks in advance. <div class="d-flex align-ite ...

Encountered a problem when implementing flowbite in a project using NextJS and TypeScript

I recently added tailwind and flowbite to my NextJS project. After importing "flowbite" in the _app.tsx file, I encountered the following error message: ReferenceError: document is not defined at Object.366 (D:\shopflo\next-tailwin ...

Angular: Issue with click() event not functioning properly once dynamic HTML is rendered

There are a few HTML elements being loaded from the server side, and an Angular click() event is also included. However, the event is not firing after the elements are rendered. It is understood that the DOM needs to be notified, but this cannot be done. ...

The completion of RxJS forkJoin is not guaranteed

After subscribing to getAllSubModules, forkJoin executes all the observables without any errors but fails to complete. Even though forkJoin should only complete after all its observables have completed, I'm seeing '-----' printed 3 times in ...

Using AsyncPipe within an ngFor loop to display items

What is the best practice for using an AsyncPipe within an ngFor loop to handle asynchronous calls for items in a list? Scenario: Imagine I have an Order object with Products, and I need to display each product's manufacturer. However, the manufactur ...

Examining form functionalities: angular2 form testing

Currently, I'm facing an issue while attempting to test a component that utilizes 'FormGroup' and 'FormBuilder'. Whenever I run the test file for this particular component, I encounter an error stating that 'FormGroup' an ...

Add a npm module without type definitions

I am currently utilizing Typescript version 2.1 and facing an issue with installing an npm package called 'reactable' that lacks typings. When attempting to import the package using import * as Reactable from 'reactable', Typescript di ...

"Trying to create a new project with 'ng new xxx' command resulted in error code -4048

Whenever I execute 'ng new projectName' in vs code, I encounter the following issue. ng new VirtualScroll ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? SCSS [ http://sass-lang.com ] CREATE Vir ...

There is no value inputted into the file

I'm facing a small issue while trying to retrieve the value from my input of type="file". Here is the code snippet: <tr ng-repeat="imagenDatos in tableImagenesPunto | filter: busquedaDatosPunto " > <td>PNG</td> <td>{{imag ...

The WebSocket connection in the browser, when accessed through a remote server, typically shows a CLOSED state in the readyState property during the on

Local server operations are running smoothly. However, when testing on a remote server with Nginx, the issue arises where the readyState inside the event handler onopen is consistently showing as CLOSED. Nginx configuration: server { server_name doma ...