Giter Club home page Giter Club logo

ngx-mat-datetime-picker's Introduction

⛔️ DEPRECATED

This is no longer supported, please consider using the repository angular-material-components/datetime-picker instead.

Ngx Material DatetimePicker, Timepicker for @angular/material 7.x, 8.x, 9.x

Build Status codecov License npm version

Description

A DatetimePicker like @angular/material Datepicker by adding support for choosing time.

button

DEMO

@see LIVE DEMO

Alt Text

Getting started

Angular 7.x, 8.x: Install the version v2.x

npm install --save [email protected]

@see DEMO stackblitz for Angular 7, Angular 8

Angular 9.x: Install the version v3.x

npm install --save [email protected]

@see DEMO stackblitz for Angular 9

Setup

Basically the same way the @angular/material Datepicker is configured and imported.

import { NgxMatDatetimePickerModule, NgxMatTimepickerModule } from 'ngx-mat-datetime-picker';
@NgModule({
   ...
   imports: [
      BrowserModule,
      HttpClientModule,
      BrowserAnimationsModule,
      MatDatepickerModule,
      MatInputModule,
      NgxMatTimepickerModule,
      FormsModule,
      ReactiveFormsModule,
      MatButtonModule,
      NgxMatDatetimePickerModule,
   ],
   ...
})
export class AppModule { }

@see src/app/app.module.ts

Using the component

The same API as @angular/material Datepicker (@see API docs)

Datetime Picker (ngx-mat-datetime-picker)

<mat-form-field>
   <input matInput [ngxMatDatetimePicker]="picker" placeholder="Choose a date" [formControl]="dateControl"
      [min]="minDate" [max]="maxDate" [disabled]="disabled">
   <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
   <ngx-mat-datetime-picker #picker [showSpinners]="showSpinners" [showSeconds]="showSeconds"
      [stepHour]="stepHour" [stepMinute]="stepMinute" [stepSecond]="stepSecond">
   </ngx-mat-datetime-picker>
</mat-form-field>

Timepicker (ngx-mat-timepicker)

<ngx-mat-timepicker [(ngModel)]="date"></ngx-mat-timepicker>
<ngx-mat-timepicker [(ngModel)]="date" [disabled]="disabled"></ngx-mat-timepicker>
<ngx-mat-timepicker [(ngModel)]="date" [stepHour]="2" [stepMinute]="5" [stepSecond]="10"></ngx-mat-timepicker>
<ngx-mat-timepicker [(ngModel)]="date" [showSpinners]="showSpinners"></ngx-mat-timepicker>
<ngx-mat-timepicker [(ngModel)]="date" [showSeconds]="showSeconds"></ngx-mat-timepicker>
<ngx-mat-timepicker [formControl]="formControl"></ngx-mat-timepicker>

List of @Input

@Input Type Default value Description
disabled boolean null If true, the picker is readonly and can't be modified
showSpinners boolean true If true, the spinners above and below input are visible
showSeconds boolean true If true, it is not possible to select seconds
stepHour number 1 The number of hours to add/substract when clicking hour spinners
stepMinute number 1 The number of minutes to add/substract when clicking minute spinners
stepSecond number 1 The number of seconds to add/substract when clicking second spinners
color ThemePalette undefined Color palette to use on the datepicker's calendar.
enableMeridian boolean false Whether to display 12H or 24H mode.
touchUi boolean false Whether the calendar UI is in touch mode. In touch mode the calendar opens in a dialog rather than a popup and elements have more padding to allow for bigger touch targets.

Choosing a date implementation and date format settings

The datepicker was built to be date implementation agnostic. This means that it can be made to work with a variety of different date implementations. However it also means that developers need to make sure to provide the appropriate pieces for the datepicker to work with their chosen implementation.

The easiest way to ensure this is to import one of the provided date modules:

NgxMatNativeDateModule NgxMatMomentModule
Date type Date Moment
Supported locales en-US See project for details
Dependencies None Moment.js
Import from ngx-mat-datetime-picker ngx-mat-moment-adapter

To use NgxMatMomentModule:

npm install --save ngx-mat-moment-adapter

Please note: NgxMatNativeDateModule is based off the functionality available in JavaScript's native Date object. Thus it is not suitable for many locales. One of the biggest shortcomings of the native Date object is the inability to set the parse format.

We highly recommend using the NgxMatMomentModule or a custom NgxMatDateAdapter that works with the formatting/parsing library of your choice.

For example:

Creating a custom date adapter:

@Injectable()
export class CustomDateAdapter extends NgxMatDateAdapter<D> {...}
// D can be Date, Moment or customized type

Creating a custom date adapter module

@NgModule({
  providers: [
    {
      provide: NgxMatDateAdapter,
      useClass: CustomDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
    }
  ],
})
export class CustomDateModule { }

Theming

<link href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block" rel="stylesheet">

License

MIT

ngx-mat-datetime-picker's People

Contributors

dependabot[bot] avatar h2qutc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

ngx-mat-datetime-picker's Issues

Cannot access 'NgxMatCalendar' before initialization

I just updated to @3.0.0 after updating a project to Angular 9 and the application cannot bootstrap throwing the following error:

Cannot access 'NgxMatCalendar' before initialization

It may be something else gone wrong with my update but just wanted to reach out in case this rings a bell to you.

Thank you!

peer dependency warning

npm WARN [email protected] requires a peer of @angular/platform-browser@~7.2.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/common@~7.2.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@~7.2.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@~7.2.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/material@~7.3.7 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/cdk@~7.3.7 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of rxjs@~6.3.3 but none is installed. You must install peer dependencies yourself.

angular 8 has been out for a while now, and 9 is around the corner.

Ability to add some validation pattern to the time inputs

  1. Currently into the time input we can type any text, on submit input is cleared and value is 00;
  2. Also we can type large numbers (example 10000), for hours, minutes and seconds. After submit value is unpredictable. Sometime it is error, sometime some huge date depends on how big number is.

Is there any way that we can prevent user to enter wrong values.
For instance:

  • User can type only numbers from 00 - 23, for hours
  • User can type only numbers from 00 - 59, for minutes
  • User can type only numbers from 00 - 59, for seconds

Cannot read property 'toString' of null

Hi,
I'm getting this error in the console when I'm trying to open the picker:

core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'toString' of null
TypeError: Cannot read property 'toString' of null
    at formatTwoDigitTimeValue (ngx-mat-datetime-picker.js:56)
    at NgxMatTimepickerComponent._updateHourMinuteSecond (ngx-mat-datetime-picker.js:1444)
    at NgxMatTimepickerComponent.writeValue (ngx-mat-datetime-picker.js:1386)
    at forms.js:3316
    at forms.js:4690
    at Array.forEach (<anonymous>)
    at FormControl.setValue (forms.js:4686)
    at forms.js:6821
    at ZoneDelegate.invoke (zone-evergreen.js:359)
    at Object.onInvoke (core.js:39699)
    at resolvePromise (zone-evergreen.js:797)
    at zone-evergreen.js:862
    at ZoneDelegate.invokeTask (zone-evergreen.js:391)
    at Object.onInvokeTask (core.js:39680)
    at ZoneDelegate.invokeTask (zone-evergreen.js:390)
    at Zone.runTask (zone-evergreen.js:168)
    at drainMicroTaskQueue (zone-evergreen.js:559)
    at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:469)
    at invokeTask (zone-evergreen.js:1603)
    at HTMLButtonElement.globalZoneAwareCallback (zone-evergreen.js:1629)

I'm not using it with FormControl, but like this:

<div>
  <input matInput [ngxMatDatetimePicker]="picker" placeholder="Choose a date" [(ngModel)]="date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <ngx-mat-datetime-picker #picker></ngx-mat-datetime-picker>
</div>

Besides using it like above, I only imported NgxMatDatetimePickerModule in app.module.ts and configured a DateAdapter in the component.

Close on click or click outside

Hi. Great job including the timepicker.

However, there's a way to close the popup when selecting a date or clicking outside? So the behaviour would be the same as the official datepicker.

Thanks!

Issue with format and parse

Hi,

I have a problem with formatting date on input.
Providing MAT_DATE_FORMATS with display.dateInput seems to always concating HH:mm:ss.

Even overriding NativeDateAdapter format function does not help.

Another problem is with NativeDateAdapter.parse function - when overrided program does not invoke it.

angular 8 bug ?

When date is not set initially, and you try to open ngx-mat-datetime-picker it breaks with this error.

[Error] ERROR
TypeError: null is not an object (evaluating 'date.clone')
clone — material-moment-adapter.js:166
open — ngx-mat-datetime-picker.js:524
_open — datepicker.js:2889
(anonymous function)
callWithDebugContext — core.js:45631
dispatchEvent — core.js:29803
(anonymous function) — platform-browser.js:2668
onInvokeTask — core.js:39679
runTask — zone-evergreen.js:168
invokeTask — zone-evergreen.js:465
invokeTask — zone-evergreen.js:1603
globalZoneAwareCallback — zone-evergreen.js:1629
error
View_MatDatepickerToggle_0 (MatDatepickerToggle.ngfactory.js:14)
logError (vendor.js:105041)
logError
handleError (vendor.js:69691)
dispatchEvent (vendor.js:90579)
(anonymous function) (vendor.js:159448)
onInvokeTask (vendor.js:99491)
runTask (polyfills.js:3174)
invokeTask (polyfills.js:3471)
invokeTask (polyfills.js:4609)
globalZoneAwareCallback (polyfills.js:4635)

FormControlName support

Am I doing something wrong or there is not support for formControlName?

component.html

<form [formGroup]="reportSettingsForm">
    <mat-form-field>
        <input matInput [ngxMatDatetimePicker]="picker" placeholder="Choose a date" formControlName="includeToDate">
         <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
         <ngx-mat-datetime-picker #picker></ngx-mat-datetime-picker>
     </mat-form-field>
</form>

component.ts

  ngOnInit() {
    this.reportSettingsForm = this.fb.group({
      ...
      includeToDate: new Date()
      ...
  }

I receiving following error after clicking on input

core.js:6406 ERROR TypeError: Cannot read property 'getTime' of null
    at NativeDateAdapter.clone (core.js:1218)
    at NgxMatDatetimePicker.open (ngx-mat-datetime-picker.js:664)
    at MatDatepickerToggle._open (datepicker.js:4342)
    at MatDatepickerToggle_Template_button_click_0_listener (datepicker.js:4388)
    at executeListenerWithErrorHandling (core.js:24283)
    at wrapListenerIn_markDirtyAndPreventDefault (core.js:24325)
    at HTMLButtonElement.<anonymous> (platform-browser.js:928)
    at ZoneDelegate.invokeTask (zone-evergreen.js:400)
    at Object.onInvokeTask (core.js:41458)
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)

Minor Accessibility Enchancements

Hi,

When using your datetime picker in a project that has accessibility in mind (e.g. WCAG), I encountered some minor problems, specifically when using screen readers.
It would be so helpful to include some of these small enhancements as they would make a big difference!

Some of the image buttons on the picker have no accessible names or labels, so screen readers don't read the functionality of these buttons to the users:

  • the checkmark button that saves the input of the picker has no textual description - you could add an aria-label="Done" attribute to the html tag of the button (the screen reader would be able to read the text "Done" to a user whenever they would change focus to the checkmark button) see the first attachment

  • the time addition and subtraction buttons seem to have identical accessible names that don't reflect their usage, such as 'expand_less icon' and 'expand_more icon' - you could add more descriptive textual descriptions to them such as "Previous Hour", "Next Minute" or so by using the aria-label attribute (the user of the screen reader could understand the usage of the button that they placed their focused on) see the second attachment

I have noticed that some of the components of the picker already have accessibility labels that screen readers can interpret. It would be great to extend this functionality.

Thank you!

image
image

'nxg-mat-datetime-picker' is not a known element

Followed the examples verbatim (code below) but keep getting this error. Any suggestions would be greatly appreciated.

Module is imported in both app.module.ts and the parent jobs.module.ts

import { NgxMatDatetimePickerModule } from 'ngx-mat-datetime-picker';
...
@NgModule({
imports: [
...
        NgxMatDatetimePickerModule,
...]
})

Template looks like this.

                        <input matInput [ngxMatDatetimePicker]="dp1" placeholder="Job start time*" formControlName="jobStartTime" required>
                        <mat-datepicker-toggle matSuffix [for]="dp1"></mat-datepicker-toggle>
                        <nxg-mat-datetime-picker #dp1 disabled="false"></nxg-mat-datetime-picker>
                        <div *ngIf="form.controls.jobStartTime.touched && !form.controls.jobStartTime.valid && form.controls.jobStartTime.errors">
                            <mat-error *ngIf="form.controls.jobStartTime.errors.required" class="alert alert-danger" >
                                Job start date required
                            </mat-error>
                            <mat-error *ngIf="form.controls.jobStartTime.errors.cannotBeforeToday" class="alert alert-danger">
                                Job cannot start before today
                            </mat-error>
                        </div>   
                    </mat-form-field>

Getting this error:

Error: Uncaught (in promise): Error: Template parse errors:
core.js:7187
message:"Uncaught (in promise): Error: Template parse errors:\n'nxg-mat-
datetime-picker' is not a known element:\n1. If 'nxg-mat-datetime-picker' is an 
Angular component, then verify that it is part of this module.\n2. If 'nxg-mat-
datetime-picker' is a Web Component then add 
'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this 
component to suppress this message. ("      <mat-datepicker-toggle matSuffix 
[for]="dp1"></mat-datepicker-toggle>\n                        [ERROR ->]<nxg-mat-
datetime-picker #dp1 disabled="false"></nxg-mat-datetime-picker>\n                        <di"): ng:///JobsModule/JobDetailItineraryEditComponent.html@31:24\nError: 
Template parse errors:\n'nxg-mat-datetime-picker' is not a known element:\n1. 
If 'nxg-mat-datetime-picker' is an Angular component, then verify that it is part 
of this module.\n2. If 'nxg-mat-datetime-picker' is a Web Component then add 
'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this 
component to suppress this message. ("      <mat-datepicker-toggle matSuffix 
[for]="d...

Disable Seconds on input

Hello everyone, i want to display only 19:20 instead 19:20:44. I don't need to display seconds for the users.

If its possible can help me? Thanks

Null value?

How can I set initial value like a null or ''? I get this error:

Captura de pantalla 2020-01-15 a las 13 10 38

Always I have to create a new Date to init component, for form with no required formControl will be necessary, what do you think?

Thanks!

Manually opening calendar in Ngx Material DatetimePicker @2.x

I am using Ngx Material DatetimePicker, version: 2.0.4 in my project for date-time picker.

I know angular material date picker has a feature called manually opening calendar. It opens the calendar on click event like (click)="picker.open()"

I am looking for same in Ngx Material DatetimePicker. Is there any way I can achieve this?

Icons not showing

The time spinners and check icons are not showing after a date is selected. Picture below of the issue.

iconsNotShowing

Setting/ posting the value of input as string not object

Hi there,
I need to post the data form as string, but when i choose the date its value is an moment object:
{_isAMomentObject: true, _isUTC: false, _pf: {…}, _locale: Locale, _d: Mon Mar 16 2020 15:02:32 GMT+0100 (czas środkowoeuropejski standardowy), …}
I'm trying to set it manual while date changes like:

changeDate(type: string, event: MatDatepickerInputEvent<Date>, i:number) {
let newdate = moment(event.target.value);
let dateToSend = moment(newdate).format('D/M/YYYY HH:mm');
this.timeFromControl(i).setValue(dateToSend);

but it doesn't work.

Do you know how to set the inputs to post the string value not the object.

Regards


EDIT: Forget about it, posting it with moment value was not the problem of bad request.

Make "_cancel" and "_ok" methods part of public API.

For now naming of methods _cancel and _api implies that they are not supposed to be called by clients. However I faced the situation when one of those methods turns out to be useful: manual closing of dialog and leaving date/time input value unchanged.

moment error on install

I installed the package on my angular 8.2.14 project, cause it looks light a lightweight addition to @angular/material

I have the following error after install.

ERROR in ./node_modules/ngx-mat-datetime-picker/fesm5/ngx-mat-datetime-picker.js
Module not found: Error: Can't resolve 'moment' in 'C:\Users\Crocsx\Documents\github\tjx-mission\node_modules\ngx-mat-datetime-picker\fesm5'

I tried to clear npm cache, redownload my modules etc.. but I need to npm install moment manually to make it works.

Is it possible to make the lib work with Native Date ?

Disable seconds

Hello, is there any way to simple deactivate/ not show seconds on the picker and the input? Regards

moment getHours : _copyTime

Hi!

After v1.0.1

fromDate.hour(), fromDate.minute(), fromDate.second() in else bracket yields errors as fromDate is not of type moment date..

_copyTime(toDate, fromDate) {
if (toDate instanceof Date) {
toDate.setHours(((/** @type {?} / (fromDate))).getHours());
toDate.setMinutes(((/
* @type {?} / (fromDate))).getMinutes());
toDate.setSeconds(((/
* @type {?} / (fromDate))).getSeconds());
}
else if (moment$1.isMoment(toDate)) {
toDate.hour(((/
* @type {?} / (fromDate))).hour());
toDate.minute(((/
* @type {?} / (fromDate))).minute());
toDate.second(((/
* @type {?} */ (fromDate))).second());
}
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.