1

I've reviewed the documentation on the Angular material datepicker and it didn't work to change to the output. I used some answers here on stackoverflow but they still only changed the displayed format. As you can see in the picture I am unable to change the datepicker output from Mon Feb 11 to the format in the datepicker's input field 11-02-2019 example. How do I get it to output the format as shown on the datepicker input line instead of Mon Feb 11 and remove the time value attached.

Here is my component.ts so far:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import {DateAdapter,NativeDateAdapter,MAT_DATE_FORMATS,MAT_DATE_LOCALE} from "@angular/material/core";
import * as moment from "moment";
import { DatabaseService } from 'src/app/database.service'
import { Observable } from 'rxjs';
const CUSTOM_DATE_FORMATS = {parse: {dateInput: { month: "short", year: "numeric", day: "numeric" }},
display: {
dateInput: "input",
monthYearLabel: { year: "numeric", month: "short" },
dateA11yLabel: { year: "numeric", month: "long", day: "numeric" },
monthYearA11yLabel: { year: "numeric", month: "long" }}};
const dateFormat = "DD-MM-YYYY";
class AppDateAdapter extends NativeDateAdapter {format(date: Date, displayFormat: Object): string {
if (displayFormat === "input") {return moment(date).format(dateFormat);}else {
  return date.toDateString();}}}
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css'],

  providers: [
     { provide: MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
     { provide: DateAdapter, useClass: AppDateAdapter }
]
})
export class DashboardComponent implements OnInit {
get data(): string {
return this.databaseService.serviceData;
}
set data(value: string) { 
this.databaseService.serviceData = (value);  } 

@Input() placeholder;
@Output() onFilter: EventEmitter<any> = new EventEmitter<any>();
@Input() selectedValue;
@Output() selectedValueChange: EventEmitter<any> = new EventEmitter<any>();

private _selectedValue;

constructor(public databaseService: DatabaseService){}

ngOnInit() {
this._selectedValue = this.data;}

onChange($event) {
this.selectedValue = this.updateDate($event.value);
this.onFilter.emit(this.data);}

updateDate(date) {
let formatedDate;
if (date !== undefined) {
  formatedDate = moment(date).format(dateFormat);
}
this.selectedValueChange.emit(formatedDate);
return formatedDate;
   }

}

And my html:

<div style="top: 50%; position: absolute;">
  <mat-form-field class="datepicker">
    <input matInput [matDatepicker]="picker" [(ngModel)]= data>
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker touchUi #picker></mat-datepicker>
  </mat-form-field>  
 <h2 >Data from A: {{ data }} </h2> 
 <input [(ngModel)] = data/>
 <a [routerLink]="['/**']">Go to B</a> 
</div>

1 Answer 1

5

Output object provided from the Material DatePicker already carry all the informations that you need, you only need to print them out correctly.

Try:

    <h2 >Data from A: {{data.format("DD-MM-YYYY")}} </h2> 

Instead of your:

    <h2 >Data from A: {{ data }} </h2> 

Just to be sure, i've tested this on a working project and it work properly.

Edit:

If you need to execute some procedure when the date is changed you need to set up a "listener" (dateChange) on datePicker input, in this way:

   ...
    <input matInput [matDatepicker]="picker" [(ngModel)]= data (dateChange)="yourFunctionName($event.value)">
   ...

$event.value have the save value of "data" so, at this point, you can remove the [(ngModel)]= data (that is deprecated in Angular 6)

Then once the listener is set you can create the function in your typescript file that handle the date change.

yourFunctionName(event: any) {
    const data = event;
    const formattedDate = data.getDate() + '-' + (data.getMonth() + 1) + '-' + data.getFullYear();
    ... do your operations with formattedDate ...
}

Now you have your date correctly formatted available in "formattedDate" variable.
If you need to access this data in your component outside this function you can declare an external variable (like "data" you already create) and reference it inside the function with this.data syntax

data: string;

yourFunctionName(event: any) {
        ...
        this.data = data.getDate() + '-' + (data.getMonth() + 1) + '-' + data.getFullYear();
        ...
    }

You can indifferently format your date using ".getDate()" & friends or using Moment.

Sign up to request clarification or add additional context in comments.

15 Comments

thanks for the help. I believe it worked for you but when I tried replacing {{data}} with {{data.format("DD-MM-YYYY")}} and it broke the calendar and the h2 tag showed up with Data from A: but it's value is blank.The input field is still saving to the database service to pass data to other components but now no calendar + no output change. I feel like it should just be as easy as adding a .format('format structure')
Try with the classic syntax for javascript Date: {{data.getDate() + "-" + (data.getMonth() + 1) + "-" + data.getFullYear()}} If this doesn't work, can you tell me which type is the "data" variable, so i can understand which function ara available for extract the information you need.
Thanks again Simo. That worked but do you know how I can store it in that format in a variable in my service. I want to pass it in that format to use to reference in my firebase database to grab data using that particular string format. So when a user clicks on the calendar it would store the date, ex, 2-2-19 and pass it to the next component where it the var is inserted into , ex db.list('documents/2-2-19')
"data" variable already store the date info, being bound with ngModel, every time you chose a different date, "data" variable is refreshed, you only need to correctly format the output. But, if i have understood correctly your last comment, you need to store this result when the date is changed so you need a event that tell you that the user have set a new date right?
In that case you can use (dateChange) in your input for trigger a function when the values in the datepicker are modified, if you need extra info about let me know that i will update my answer, explain implementation of dateChange is a little unhandy in a comment.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.