I want to use the component DatePicker in Angular, to receive a date with the possibility to be translate in according to the Browser translate/locale. How Can I do?
<mat-form-field appearance="fill">
<mat-label>Choose a date</mat-label>
<input matInput [matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
Ciao, when you got the date from datepicket, you could get browser locale in this way:
var locale = window.navigator.userLanguage || window.navigator.language;
then you could use moment to visualize date in current locale like this. See this small example:
let yourdatefromdatepicker = moment();
// get locale from browser
var locale = window.navigator.userLanguage || window.navigator.language;
//print current locale
console.log(moment.locale(locale));
// yourdatefromdatepicker date in current locale
console.log(yourdatefromdatepicker.locale(locale))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
If you want to set a default language for all material components in your Angular application you can do the following:
In your app module you should import the MAT_DATE_LOCALE and LOCALE_ID, the registration function and the locale you want to add (in my case Dutch):
import { MatNativeDateModule, MAT_DATE_LOCALE } from '#angular/material/core';
import { registerLocaleData } from '#angular/common';
import localeNl from '#angular/common/locales/nl';
import { LOCALE_ID } from '#angular/core';
Then you must register the locale:
registerLocaleData(localeNl);
Finally you must provide the new locale:
providers: [
{ provide: MAT_DATE_LOCALE, useValue: 'nl-NL' },
{ provide: LOCALE_ID, useValue: 'nl-NL' }
]
This will make all your material components use the language that you set here.
For more information about which languages are supported by Angular refer to this link.
Related
I have created a custom directive for checking manual entries in angular material date picker (with help of here), and it is working.
Q: Is there any way to add that directive to all instances that are already present in the project without adding the directive one by one?
My directive:
import { Directive, ElementRef, HostBinding, OnDestroy, OnInit } from '#angular/core';
import * as textMask from '../../../util/vanillaTextMask.js';
#Directive({
selector: `fed-mask, [fed-mask], [fedMask]`
})
export class FedMaskDirective implements OnInit, OnDestroy {
#HostBinding('class.fed-mask') compClass = true;
fedMask = {
mask: [
new RegExp('\\d'),
new RegExp('\\d'),
'.',
new RegExp('\\d'),
new RegExp('\\d'),
'.',
new RegExp('\\d'),
new RegExp('\\d'),
new RegExp('\\d'),
new RegExp('\\d')
],
showMask: false,
guide: false,
placeholderChar: '_'
};
maskedInputController;
constructor(private element: ElementRef) { }
ngOnInit(): void {
this.maskedInputController = textMask.maskInput({
inputElement: this.element.nativeElement,
...this.fedMask
});
}
ngOnDestroy() {
this.maskedInputController.destroy();
}
}
how I'm currently using it:
<mat-form-field>
<input
(dateChange)="DateChange($event)"
formControlName="Date"
[matDatepicker]="Datepicker"
matInput
placeholder="Date"
(click)="Datepicker.open()"
fedMask
>
<mat-datepicker-toggle matSuffix [for]="Datepicker"></mat-datepicker-toggle>
<mat-datepicker #Datepicker></mat-datepicker>
<mat-error *ngIf="form.get('Date').hasError('required')">
Error
</mat-error>
</mat-form-field>
Expectation:
is there any way to add the fedMask directive to every instance of material date picker input without manually adding it for every time it has been used in the whole project?
you can use any existing attribute as a selector, for example
#Directive({
selector: "matDatepicker",
})
will target every element that has the attribute matDatepicker present on it.
Another example:
#Directive({selector: 'input:([matDatepicker])' })
will target every input with the matDatepicker attribute.
The same goes for tags:
#Directive({
selector: "mat-datepicker",
})
How do I create a Month and Day Date Picker in Angular, excluding hide year?
This following link will do a Month and Year picker. I am trying to manipulate it, to do Month and Day. Replacing YYYY with DD is not working.
Stackblitz:
https://stackblitz.com/angular/gxymgjpprdy?file=src%2Fapp%2Fdatepicker-views-selection-example.ts
Real code from Stackblitz:
Typescript:
import {Component} from '#angular/core';
import {FormControl} from '#angular/forms';
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '#angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '#angular/material/core';
import {MatDatepicker} from '#angular/material/datepicker';
// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment, Moment} from 'moment';
const moment = _rollupMoment || _moment;
// See the Moment.js docs for the meaning of these formats:
// https://momentjs.com/docs/#/displaying/format/
export const MY_FORMATS = {
parse: {
dateInput: 'MM/YYYY',
},
display: {
dateInput: 'MM/YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
/** #title Datepicker emulating a Year and month picker */
#Component({
selector: 'datepicker-views-selection-example',
templateUrl: 'datepicker-views-selection-example.html',
styleUrls: ['datepicker-views-selection-example.css'],
providers: [
// `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your
// application's root module. We provide it at the component level here, due to limitations of
// our example generation script.
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
],
})
export class DatepickerViewsSelectionExample {
date = new FormControl(moment());
chosenYearHandler(normalizedYear: Moment) {
const ctrlValue = this.date.value;
ctrlValue.year(normalizedYear.year());
this.date.setValue(ctrlValue);
}
chosenMonthHandler(normalizedMonth: Moment, datepicker: MatDatepicker<Moment>) {
const ctrlValue = this.date.value;
ctrlValue.month(normalizedMonth.month());
this.date.setValue(ctrlValue);
datepicker.close();
}
}
HTML:
<mat-form-field>
<input matInput [matDatepicker]="dp" placeholder="Month and Year" [formControl]="date">
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp
startView="multi-year"
(yearSelected)="chosenYearHandler($event)"
(monthSelected)="chosenMonthHandler($event, dp)"
panelClass="example-month-picker">
</mat-datepicker>
</mat-form-field>
I do not want year option below in green, would like to disable year
Other Resources:
https://material.angular.io/components/datepicker/overview#watching-the-views-for-changes-on-selected-years-and-months
Angular Material Date picker disable the year selection
I hope you are expecting date format like DD/MMM. If so then change dateInput in display and parse object like below
dateInput: 'DD/MMM'
Hope this helps.
Here is the stackblitz code.
https://stackblitz.com/edit/angular-hw54xf
So , first in the html file
<mat-form-field class="mat-50-left" (click)="updateCalendarUI()">
<input matInput [matDatepicker]="picker_start"
placeholder="Date de début" required formControlName="dt_start" (click)="picker_start.open();">
<mat-datepicker-toggle matSuffix (click)="picker_end.open(); updateCalendarUI()"></mat-datepicker-toggle>
<mat-datepicker #picker_start startView="year"></mat-datepicker>
</mat-form-field>
in the .ts file
import {DateAdapter, NativeDateAdapter} from "#angular/material/core";
import * as moment from "moment";
export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
// use what format you need
return moment(date).format('DD MMM');
}
}
add in providers
providers: [{provide: DateAdapter, useClass: AppDateAdapter}]
To update calendar UI
updateCalendarUI(): void {
setTimeout(() => {
let calendar = document.getElementsByClassName('mat-
calendar').item(0);
if (calendar) {
calendar['style'].height = '275px';
calendar['style']['padding-top'] = '15px';
}
let header = document.getElementsByClassName('mat-calendar-
header').item(0);
if (header) {
header['style'].display = 'none';
}
let yearLabel = document.getElementsByClassName('mat-calendar-body-
label').item(0);
if (yearLabel) {
yearLabel['style'].display = 'none';
}
}, 1);
}
I have the form for date filter and I trying set the default value for the start and end date for date inputs.
<form [formGroup]="filter" (ngSubmit)="applyFilter()">
<mat-form-field>
<input matInput [matDatepicker]="start" formControlName="start" placeholder="Начальная дата">
<mat-datepicker-toggle matSuffix [for]="start"></mat-datepicker-toggle>
<mat-datepicker #start></mat-datepicker>
</mat-form-field>
<mat-form-field>
<input matInput [matDatepicker]="end" formControlName="end" placeholder="Конечная дата">
<mat-datepicker-toggle matSuffix [for]="end"></mat-datepicker-toggle>
<mat-datepicker #end></mat-datepicker>
</mat-form-field>
And TS part
refreshFilter() {
const now = new Date();
const monthAgo = new Date().setMonth(now.getMonth() - 1).toString();
console.log(monthAgo)
console.log(now)
this.filter = new FormGroup({
start: new FormControl(monthAgo, []),
end: new FormControl(now, [])
});
}
My console.log() for the month ago is 1533908066234 but for new Date is Mon Sep 10 2018 16:34:26 GMT+0300 and with timestamp form input doesn't work. How to get correct format date of month ago for success setting into FormControl?
If you Want to format a date in Angular you can use the DatePipe
Try to use the pipe to format.
This allows you to format a date value according to locale rules.
If you need more info about this you also can check here:
https://angular.io/api/common/DatePipe
Also do this monthAgo.toLocaleDateString()
I hope this helps!
I followed the following steps and it worked as expected:
created a new Angular 6 app using CLI and added Angular Materials to project
imported FormsModule and ReactiveFormsModule in app.module.ts
copied exactly the same html markup as you provided into app.component.html
added the below code in app.component.ts
import { Component, OnInit } from '#angular/core';
import {FormControl, FormGroup} from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
filter: FormGroup
ngOnInit() {
let now = new Date();
let monthAgo = new Date();
monthAgo.setMonth(now.getMonth() - 1);
this.filter = new FormGroup({
start: new FormControl(monthAgo, []),
end: new FormControl(now, [])
});
}
}
Hope this helps.
I found the solution:
const now = new Date();
const monthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate(), now.getHours());
this.filter = new FormGroup({
start: new FormControl(monthAgo , []),
end: new FormControl(now, [])
});
I converting the date from timestamp to string format. That's all.
If somebody knows how to rewriting this more elegantly, I would be grateful.
Currently, I am getting date time in the following format 'mm/dd/yyyy, hh:mm:ss'.
How to get it in the following format 'mm-dd-yyyy hh-mm-ss'.
How to achieve this without using any library, and preferably by passing some args to the function itself?
Below is the code that am currently using (in Angular 5)
console.log(new Date().toLocaleString(undefined, { hour12: false }));
make use of DatePipe , that is provided by angular framework
{{ strDate | date :'MM-dd-yyyy hh-mm-ss' }
or in code you can do like this
import { DatePipe } from '#angular/common';
#Component({
selector: 'test-component',
templateUrl: './test-component.component.html'
})
class TestComponent {
constructor(private datePipe: DatePipe) {}
formatDate(date= new Date()) {
return this.datePipe.transform(date,'MM-dd-yyyy hh-mm-ss' );
}
}
check here : DatePipe
How to Change language of Datepicker of Material Angular?
I can't find in documentation for Angular material 2.
Here is a plunkr https://plnkr.co/edit/unzlijtsHf3CPW4oL7bl?p=preview
<md-input-container>
<input mdInput [mdDatepicker]="picker" placeholder="Choose a date">
<button mdSuffix [mdDatepickerToggle]="picker"></button>
</md-input-container>
<md-datepicker #picker></md-datepicker>
import {MAT_DATE_LOCALE} from '#angular/material';
&
providers: [{ provide: MAT_DATE_LOCALE, useValue: 'es-ES' }]
Do this in tpv.modules.ts
md-datepicker provides setLocale method which can be used to set any language (list of locale).
Here's an example of setting locale to 'fr':
export class DatepickerOverviewExample {
constructor(private dateAdapter: DateAdapter<Date>) {
this.dateAdapter.setLocale('fr');
}
}
One thing to keep in mind, md-datepicker's default date parsing format is mm/dd/yyyy, so if a locale has a different date format (for 'fr' its dd/mm/yyyy), we will need to define a class that extends NativeDateAdapter to parse the new date format. Without setting the proper date format, there will be an issue like this question.
import { NativeDateAdapter, DateAdapter, MD_DATE_FORMATS } from "#angular/material/core";
export class FrenchDateAdapter extends NativeDateAdapter {
parse(value: any): Date | null {
if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
const str = value.split('/');
if (str.length < 2 || isNaN(+str[0]) || isNaN(+str[1]) || isNaN(+str[2])) {
return null;
}
return new Date(Number(str[2]), Number(str[1]) - 1, Number(str[0]), 12);
}
const timestamp = typeof value === 'number' ? value : Date.parse(value);
return isNaN(timestamp) ? null : new Date(timestamp);
}
}
#Component({
...
providers: [{provide: DateAdapter, useClass: FrenchDateAdapter}],
})
Plunker demo
Locale setting can be provided via MAT_DATE_LOCALE constant, but to change language dynamically you need to use DateAdapter as it is shown in https://material.angular.io/components/datepicker/overview#internationalization
#Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor(private dateAdapter: DateAdapter<any>) {}
setFrench() {
// Set language of Datepicker
this.dateAdapter.setLocale('fr');
}
}
Here is another example when you need to configure locale from external script:
<script>
window.appConfig = {
language: 'fr',
// Other config options
// ...
};
<script>
<app-root></app-root>
In this case you should also use DateAdapter:
import {Injectable} from '#angular/core';
import {DateAdapter} from '#angular/material';
declare let window: any;
#Injectable()
export class AppConfigService {
appConfig = window.appConfig;
constructor(private dateAdapter: DateAdapter<any>) {
// Set language of Datepicker
this.dateAdapter.setLocale(this.appConfig.language);
}
}
For anyone who has a bug when editing input field (eg: putting DD/MM/YYYY will change it to MM/DD/YYYY or simply not working) create an adapter:
import { NativeDateAdapter } from '#angular/material';
export class FrenchDateProvider extends NativeDateAdapter {
parse(value: string) {
let it = value.split('/');
if (it.length == 3) {
return new Date(+it[2], +it[1] - 1, +it[0], 12);
}
}
format(date: Date, displayFormat: Object) {
return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear();
}
}
Add it to your module as provider:
#NgModule({
providers: [
{ provide: DateAdapter, useClass: FrenchDateProvider }
]
})
export class SharedModule { }
For me the working solution is similar to vladernn's, however it should be:
import {MAT_DATE_LOCALE} from '#angular/material/core';
and
providers: [{ provide: MAT_DATE_LOCALE, useValue: 'pl' }]
in material.module.ts file.
Difference: new import address and shorter useValue code.
I tried this and worked for me
constructor(private _adapter: DateAdapter<any>, private translate:TranslateService ) {
this._adapter.setLocale(this.translate.getBrowserLang());
}