How to have a 2-way formatter for input-field?

Viewed 283

I like to 2-way bind a Date to an input-control.

public dtm : Date;
...
this.dtm = new Date ();

...

<input type="text" placeholder="DD.MM.YYYY" [(ngModel)]="dtm"/>

If I do so then the input will show the date in its standard-format.

e.g. Sat Oct 19 2019 11:53:00 GMT+0200 (CEST)

Is it possible to have a form of 2-way (!) formatter for a special format (e.g. DD.MM.YYYY)?

I like to have a instance of Date in the code but also have a formatted output (Date -> DD.MM.YYYY) and a parsing of the input (DD.MM.YYYY -> Date).

EDIT At least I want to have a 2-way bind and a output-formatter. But I am not sure how to have [(ngModel)] and a date-pipe in place.

2 Answers

In my opinion, we could not have the 2-way binding directly. Here is a workaround

<input type="date" [ngModel]="dtm | date:'yyyy-MM-dd'" (input)="dtm=$event.target.valueAsDate" />

or

<input type="text" [ngModel]="dtm1 | date:'shortDate'" (ngModelChange)="dtm1=parseDate($event)" /> 

With parseDate is a function to parse a string to a date.

You could define a custom DatePipe as you like if Angular DatePipe doesn't meet your needs.

Here is a simple StackBlitz.

if I understand it correctly then you can use DatePipe in TS itself to format the date as per your requirements:

Imports:

import { DatePipe } from "@angular/common"

HTML:

<mat-form-field>
    <input matInput [matDatepicker]="dp1" [(ngModel)]="dtm" (dateInput)="change($event.target.value, $event)" placeholder="Choose a date">
    <mat-datepicker-toggle matSuffix [for]="dp1"></mat-datepicker-toggle>
    <mat-datepicker #dp1></mat-datepicker>
</mat-form-field>

TS Code:

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

@Component({
  selector: "table-filtering-example",
  styleUrls: ["table-filtering-example.css"],
  templateUrl: "table-filtering-example.html",
  providers: [DatePipe] -- Add in Providers array
})
export class TableFilteringExample {
  public dtm: Date;
  selectedDate: any;

  constructor(public datepipe: DatePipe) { --Inject here
    this.dtm = new Date();
  }

  change(date: string, event) {
    if (event.value != undefined) {
      this.selectedDate = this.datepipe.transform(date, "M/d/yyyy");
      console.log(this.selectedDate);
    }
  }
}

StackBlitz Demo

Related