Displaying Date in Angular 2 Application with Proper Formatting

I'm currently working on formatting the date pipe in my Angular application to display correctly when used within an input template. Originally, without the date formatting, my code looked like this:

<input class="app-input" [readonly]="!hasAdminAccess"                                  
    [(ngModel)]="staff.profile.hireDate" placeholder="None"
    [field-status]="getPropertyStatus('profile.hireDate')"/>

The closest I've come to using the date pipe is as follows:

<input class="app-input"
{{ staff.profile.hireDate | date:'shortDate' }} placeholder="None"
[field-status]="getPropertyStatus('profile.hireDate')"/>

However, the output in the view displays the following (exactly as shown):

> <input class="app-input" 3/18/2014 placeholder="None"
> [field-status]="getPropertyStatus('profile.hireDate')"/>

As you can see, the date is correctly formatted as:

3/18/2014

But I want only the date to be displayed. I've attempted various adjustments but have yet to achieve the desired outcome. Any suggestions on how to modify the syntax to only show the date?

Answer №1

To modify the ngModel after it has been set in typescript, you can utilize the get and set functions along with the ngModelChanged property.

Component Template :

<input class="app-input" [(ngModel)]="hireDate" (ngModelChange)="dateChanged($event)"/>

Component Class :

import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <button (click)="setDate()">Set Date</button>
      <input class="app-input" readonly="true" [(ngModel)]="hireDate" (ngModelChange)="dateChanged($event)" placeholder="None"/>
    </div> 
  `,
})
export class App {
  name:string;
  staff: any;
  myDate: any;
  private _hireDate;

  dateChanged(value) {
    this.hireDate = this.datePipe.transform(value, 'shortDate');
  }

  set hireDate(value) {
    this._hireDate = this.datePipe.transform(value, 'shortDate');
  }

  get hireDate() {
    return this._hireDate;
  }

  setDate() {
    this.hireDate = '10-03-1993';
  }

  constructor(private datePipe: DatePipe) {
  }
}

The input value will be updated upon any changes, potentially causing a UX issue. Users may prefer entering their desired date manually. One workaround is triggering the date change function only after the user has inputted their date (e.g. via a button click).

The set and get functions typically apply to class variables, but for object properties like yours, you can adjust the set function to update the object property as shown below:

  set hireDate(value) {
    this._hireDate = this.datePipe.transform(value, 'shortDate');
    this.staff.profile.hireDate = this._hireDate;
  }

A plunkr example is available here.

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

Leveraging the power of the wildcard feature to execute a variety of scripts when running

Inside my package.json file, I currently have the following scripts block: "scripts": { "test": "node tests/*-test.js" } In the tests folder, I have files named a-test.js and b-test.js. This can be confirmed by using the command ls tests/*-test.js. ...

Using AngularJS directives in Markdown

I am currently working on creating a custom HTML directive using AngularJS that will allow me to display Markdown content in the browser. My goal is to have a <markdown> element with a src attribute that will dynamically load and render the specified ...

Eliminate redundant entries from an Ionic3 array

Looking for a solution to eliminate duplicate values in the storage array within Ionic3 this.storage.get('thestations').then((val) => { for(let i =0;i<val.length;i++){ if(this.newarray.indexOf(this.newarray) == -1) ...

What is the best way to navigate through a webpage to find a specific folder and show its contents on the page?

My goal is to design a webpage where users can browse their computer for a specific folder, select it, and have its content displayed on the webpage. I am fairly new to creating pages, but I want to develop a platform where you can easily find and view f ...

Enhancing the efficiency of a Puppeteer web scraping operation

app.get("/home", async (req, res) => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); const pageNumber = req.query.page || 1; await page.goto(`https://gogoanimehd.io/?page=${pageNumber ...

I need to search through a tree structure in typescript based on a specific value without encountering a maximum stack call exceeded error

How can I perform a value-based search on a complex tree structure in TypeScript without encountering the maximum stack call exceeded error? I am attempting to navigate through an expandable tree using TypeScript, and I will provide the code snippet below ...

Leveraging Ajax to send JSON data to PHP session

I am attempting to send some JSON data to a PHP file, which will then create a session. I have two different JSON blocks that need to be added to their respective PHP sessions. Could someone please assist me in finding the issue? The sessions are not bein ...

Struggling with parsing JSON strings into PHP arrays

I'm looking to transmit a JSON string using JavaScript and later convert it into an array using a PHP encoding function. After successfully converting the string in JavaScript and transmitting it via Ajax to a PHP page, I am encountering difficulties ...

The "library" is encountering errors due to missing dependencies, specifically @angular/material/form-field

I've been working with a shared component library project that has been running smoothly for a while now. Recently, I decided to replace some of the custom components with Angular Material components. However, after adding NgMat to the library project ...

What is the best way to send data from a child component to a parent component in Angular 2?

I want to retrieve data from my child component, which contains a form in a popup. How can I pass all the details to the parent component? Here is the TypeScript file for my parent component: import { Component, OnInit } from '@angular/core' ...

Deriving the type of a generic parameter from another generic parameter in TypeScript

Apologies for the less-than-descriptive title of this question, but sometimes it's easier to demonstrate with code rather than words. Here's a snippet that's causing issues, and I'm wondering why it's not behaving as expected: int ...

Utilize Javascript/Jquery to categorize JSON data based on the days of the week (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)

A function is provided below that retrieves data for a chart. The output produced by this function is structured as follows: [Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, vo ...

Please place the accurate image inside the designated box based on the corresponding ID number

I am currently working on a function that retrieves image data from a database and displays it in HTML using *ngFor directive. In order to display the correct image, I need to fetch the ID associated with the image data and use it to retrieve the correspo ...

How to inject a variable into an AngularJS service that utilizes both $http and $interval functions?

Struggling with $http and $interval, I stumbled upon this code. http://embed.plnkr.co/fSIm8B/script.js I forked it here: http://plnkr.co/edit/Al8veEgvESYA0rhKLn1q To make it more functional, how can I pass a variable to the service? Here is the broken ...

Template displaying multiple polymer variables side by side

Here is the date object I am working with: date = { day: '05' } When I use this code: <div>{{date.day}}</div> It generates the following HTML output: <div>05</div> Everything looks good so far. Now, I want to try th ...

I have a JSON object with a nested "src" value that I want to display on my webpage using Vue. How can I target and select this specific value?

I am currently working with an API and attempting to access a nested object within the JSON data named "Species Illustration Photo". Inside this object is an "img" property with the source link. How can I display this nested img source in my HTML using Vue ...

Is there a way to determine if silent login is feasible with adaljs-angular4?

I'm currently utilizing the library [email protected] for an Angular 6 project. I am attempting to achieve the following: If a silent login (login without requiring user input) with Office365 is achievable, then perform a silent login (using ...

Attempting to display my ejs template from a node server following the activation of a delete button, all without utilizing ajax

I have created a basic blog application using node.js for the backend and ejs for the frontend. Posting blogs using a web form works well by calling a post route. Now, I am facing an issue with implementing a delete button for each blog post. The current s ...

Accessing a single element from a nested object in Handlebars.js

Recently, I have been working on a nodejs application that utilizes handlebars js as its view engine. My main challenge at the moment is accessing one specific element from a nested object that I am passing to the hbs view. router.get('/view_users/:i ...

Issue encountered while attempting to save hook arrays: Uncaught TypeError - 'choices' is not able to be

I'm in the process of creating a straightforward multiple-choice exam form that includes choices and answers. Whenever a user selects an option, it should be added to the array of choices. At the start, I have an array called exercises, which consist ...