Minimum and Maximum Constraints for Date and Time Pickers

A simple exercise in functional React/JavaScript that exemplify a common use-case with date pickers.

In the following I will refer to the widely used react-datepicker component, although the considerations I will make can be applied to any date picker that provides similar capabilities.

The Problem

React-datepicker component provides two properties to constraint the selection of dates: minDate and maxDate.

When the minDate property is set, previous days cannot be selected and browsing to previous months is inhibited. The same happens in the opposite direction with maxDate.

If you enable the time picker section and specify a minDate that contains a minimum time, the expected behavior would be to have the same type of constraint in the time picker as well: the selection of times before the minDate time should not be enabled.

Well, this is not the case: times before the minimum time can still be selected.

To constraint the selection of times, the component provides two additional properties: minTime and maxTime.

Their operation is subject to the following rules:

  • Both must be set to take effect. For example, to disable the selection of times before 08:30AM, minTime must be set at 08:30 AM and maxTime must be set at 11:59PM
  • When specified, the constraints are applied regardless of the selected day. Therefore, to apply them correctly, the two properties must be related to the current selected day.

#datepicker #javascript #react #programming

What is GEEK

Buddha Community

Minimum and Maximum Constraints for Date and Time Pickers
Mike  Kozey

Mike Kozey

1655243220

A Weather_widget Used for Flutter with Many Custom Config

weather_widget

Simple weather related widget, which can be freely combined to form a variety of weather backgrounds

Getting Started

depend

Add this to your package's pubspec.yaml file:

dependencies:
  weather_widget: ^1.0.6

Weatherwidget is easy to use, just add weatherwidget to start using

WeatherWidget(
             size:Size.infinite,
             weather:'Sunny',
             sunConfig:SunConfig()
         ),   

This will add a sunny day using the default settings
sunny
or other weather type
(Note: Raindrops and snowflakes need to specify the default number, and they will move randomly within the range)

WeatherWidget(
             size:Size.infinite,
             weather:'Cloudy',
             cloudConfig:CloudConfig()
         ),

WeatherWidget(
             size:Size.infinite,
             weather:'Rainy',
             rainConfig:RainConfig(
              rainNum:'the num of raindrops you want' 
             )
         ),


WeatherWidget(
             size:Size.infinite,
             weather:'Snowy',
             snowConfig:SnowConfig(
              snowNum:'the num of snowflakes you want' 
             )
         ),


WeatherWidget(
             size:Size.infinite,
             weather:'Thunder',
             thunderConfig:ThunderConfig()
         ),

rainy snowy thunder

Of course, each config contains other settings, such as the range, size, length, falling speed and color of random raindrops. You can use them to create hailstones and other weather features
If the default weather is not enough, you can use individual widgets and stack() widget to piece together the desired weather
Like this sunset breeze, etc
sunset breeze snow with rain thunder with rain
These are include in this widget
background

    BackgroundWidget(List<Color>,size)

cloud

    CloudWidget (Color)

A single random raindrop

RainWidget (
                         @required rainRangeXStart, #X-axis starting point of raindrop random occurrence
                         @required rainRangeXEnd,  
                         @required rainRangeYStart,
                         @required rainRangeYEnd,
                         @required durationRangeStartMill,  #Minimum time to fall
                         @required durationRangeEndMill,    
                         rainLength,
                         rainWidth,
                         rainColor,
                         rainCurve  #Curve of falling animation
                         )

A single random snowflake

SnowWidget (
                         this.snowAreaXStart,  #X-axis starting point of snowflake random occurrence
                         this.snowAreaXEnd,    
                         this.snowWaveRangeMin,    #The minimum floating distance of snowflakes
                         this.snowWaveRangeMax,    
                         this.snowFallSecMin,  #Minimum time of snowflake falling
                         this.snowFallSecMax,  
                         this.snowWaveSecMin,  #Minimum time for snowflake to float
                         this.snowWaveSecMax,
                         this.snowSize,
                         this.snowColor,
                         this.snowAreaYStart,   #Y-axis point of snowflake occurrence
                         this.snowAreaYEnd,    
                         this.waveCurve,        #Floating animation curve
                         this.fadeCurve         #Vanish animation curve
)

A single flash

ThunderWidget (
                         this.flashMillStart,   #Minimum flashing time
                         this.flashMillEnd,     
                         this.pauseMillStart,   #Minimum interval time
                         this.pauseMillEnd,     
                         this.blurStyle,        #blur model
                         this.blurSigma,        
                         this.points,
                         this.color,
                         this.width
)

a single wind

WindWidget (
                        this.pauseMillStart,    #Minimum interval time
                        this.pauseMillEnd,     
                        this.windPositionY,     #Y-axis point of wind occurrence
                        this.windSlideMill,     #Passing time
                        this.windColor,
                        this.windWidth,
                        this.windSlideXEnd,     
                        this.windSlideXStart,   
                        this.windGap,           #line spacing in a wind
                        this.blurStyle,
                        this.blurSigma
)

Using sunny weather by set the WeatherWidget background config in a sunConfig()

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add weather_widget

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  weather_widget: ^1.0.6

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:weather_widget/WeatherWidget.dart';
import 'package:weather_widget/example/main.dart';

example/main.dart

import 'package:flutter/material.dart';
import 'package:weather_widget/WeatherWidget.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: WeatherWidget(
          size: Size.infinite,
          weather: 'Thunder',
          thunderConfig:ThunderConfig(
            thunderWidth:12
          )
    )
    );
  }
}

chinese 中文README

Author: Carendule
Source Code: https://github.com/carendule/WeatherWidget 
License: View license

#flutter #dart #widget 

Hal  Sauer

Hal Sauer

1591688078

Python Datetime Tutorial: Manipulate Times, Dates, and Time Spans

Dealing with dates and times in Python can be a hassle. Thankfully, there’s a built-in way of making it easier: the Python datetime module.

datetime helps us identify and process time-related elements like dates, hours, minutes, seconds, days of the week, months, years, etc. It offers various services like managing time zones and daylight savings time. It can work with timestamp data. It can extract the day of the week, day of the month, and other date and time formats from strings.

#data science tutorials #calendar #date #dates #datetime #intermediate #python #time #time series #times #tutorial #tutorials

Saul  Alaniz

Saul Alaniz

1650810840

Angular Datepicker: Cómo Usar Datepicker En Angular 13

Angular Material  está funcionando desde cero con componentes de interfaz de usuario significativos y modernos que funcionan en la web , dispositivos móviles y computadoras de escritorio

Los componentes de Angular Material nos ayudarán a construir una interfaz de usuario y una experiencia de usuario atractivas , páginas web y aplicaciones web consistentes y funcionales, manteniendo los principios de diseño web modernos, como la portabilidad y compatibilidad del navegador, la independencia del dispositivo y la degradación elegante.

Selector de fecha angular

Angular Datepicker es un componente de material incorporado que nos permite ingresar la fecha a través de la entrada de texto o eligiendo la fecha de un calendario. Angular Material Datepicker permite a los usuarios ingresar la fecha a través de la entrada de texto o eligiendo la fecha del calendario. Material Datepicker consta de varios componentes y directivas que funcionan juntos.

Se compone de varios componentes angulares y directivas que funcionan en conjunto. Primero, necesitamos instalar Angular. Estamos usando  Angular CLI para instalar  Angular.

Paso 1: Instale la CLI angular.

Escriba el siguiente comando.

npm install -g @angular/cli

Ahora, crea el proyecto Angular usando el siguiente comando.

 

ng new datepicker

Paso 2: Instale otras bibliotecas.

Ingrese al proyecto e instale  hammerjs  usando el siguiente comando.

npm install --save hammerjs

Hammer.js es la dependencia opcional y ayuda con la compatibilidad táctil para algunos componentes.

Ahora, instale  Angular Material Angular Animations  usando el siguiente comando.

npm install --save @angular/material @angular/animations @angular/cdk

Ahora, incluya  hammerjs  dentro del  archivo angular.json  . Puede encontrar este archivo en la raíz del proyecto.

Paso 3: importa un tema preconstruido e íconos de materiales.

Angular Material viene con algunos temas prediseñados. Estos temas han resaltado los colores y el estilo básico.

Los principales temas disponibles son  rosa índigoámbar morado oscuro ,  verde púrpura  y  gris azulado rosa .

Para importar el tema, puede agregar el siguiente código a su archivo global  styles.css  . El archivo está dentro de la carpeta src  .

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

También puede acceder a los íconos de Material Design  y usar íconos con nombre con un   componente <mat-icon> .

Si queremos importarlos a su proyecto, podemos agregar esto a la sección principal del   archivo raíz index.html de su proyecto.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Datepicker</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Paso 4: cree un archivo de módulo de material personalizado.

Dentro de la carpeta src,>> app  , cree un archivo llamado  material.module.ts  y agregue el siguiente código.

// material.module.ts

import { NgModule } from '@angular/core';
import { MatDatepickerModule } from '@angular/material';

@NgModule({
  imports: [
    MatDatepickerModule
  ],
  exports: [
    MatDatepickerModule
  ]
})

export class MaterialModule {}

Hemos importado MatDatepickerModule, MatNativeDateModule  y otros componentes que necesitamos en nuestra  aplicación de ejemplo Angular Datepicker  .

Podemos agregar componentes adicionales en el futuro si es necesario.

Este archivo se escribe solo porque es fácil incluir todos los componentes de Material en este archivo, y luego este archivo se importará dentro de  app.module.ts.

// material.module.ts

import { NgModule } from '@angular/core';
import { MatDatepickerModule,
        MatNativeDateModule,
        MatFormFieldModule,
        MatInputModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [
    MatDatepickerModule,
    MatFormFieldModule,
    MatNativeDateModule,
    MatInputModule,
    BrowserAnimationsModule
  ],
  exports: [
    MatDatepickerModule,
    MatFormFieldModule,
    MatNativeDateModule,
    MatInputModule,
    BrowserAnimationsModule
  ],
  providers: [ MatDatepickerModule ],
})

export class MaterialModule {}

Paso 5: importe MaterialModule en un archivo app.module.ts.

Importe MaterialModule dentro del archivo app.module.ts  .

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { MaterialModule } from './material.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MaterialModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Además, finalmente, escriba el código HTML de Datepicker dentro del archivo app.component.html  .

<!-- app.component.html -->

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

Guarde el archivo, vaya a una terminal o cmd e inicie Angular Development Server.

ng serve --open

Ejemplo de selector de fecha angular |  Cómo usar el selector de fechas en Angular

Vaya al navegador y vea algo como la imagen de abajo.

Tutorial de ejemplo de selector de fechas de Angular 6Paso 6: Conectar un selector de fechas a una entrada

Un selector de fecha consta de entrada de texto y una ventana emergente de calendario, conectados a través de la propiedad matDatePicker  en la entrada de texto.

<input [matDatepicker]="myDatepicker">
<mat-datepicker #myDatepicker></mat-datepicker>

Hay un botón de alternar selector de fecha opcional disponible. El botón de alternar se puede agregar al ejemplo anterior:

<input [matDatepicker]="myDatepicker">
<mat-datepicker-toggle [for]="myDatepicker"></mat-datepicker-toggle>
<mat-datepicker #myDatepicker></mat-datepicker>

Funciona de la misma manera con una entrada que es parte de un <mat-form-field> y un botón de alternar se puede usar fácilmente como prefijo o sufijo en la entrada de material:

<mat-form-field>
  <input matInput [matDatepicker]="myDatepicker">
  <mat-datepicker-toggle matSuffix [for]="myDatepicker"></mat-datepicker-toggle>
  <mat-datepicker #myDatepicker></mat-datepicker>
</mat-form-field>

Paso 7: Configuración de la vista de inicio del calendario

La  propiedad startView  de <mat-datepicker> podría usarse para establecer el aspecto que se mostrará cuando se abra el calendario por primera vez. Puede configurarse para  mesañovarios años ; de forma predeterminada, comenzará a ver el mes.

Un mes, año o rango de años en los que se abre un calendario se determina comprobando primero si alguna fecha está actualmente seleccionada y, de ser así, se abrirá en un mes o año que contenga esa fecha. De lo contrario, se abrirá en un mes o año, proporcionando la fecha de hoy.

Este comportamiento se puede anular fácilmente usando la  propiedad startAt de <mat-datepicker> . En este caso, se abrirá un calendario en el mes o año que contiene la  fecha startAt  .

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker startView="year" [startAt]="startDate"></mat-datepicker>
</mat-form-field>

Tutorial de ejemplo de selector de fecha de material angular

Puedes encontrar el código en Github.

CÓDIGO GITHUB

Validación de selector de fecha angular

Tres propiedades agregan la validación de fecha a la entrada del selector de fecha.

Los dos primeros son las propiedades min y max .

Además, para hacer cumplir la validación en la entrada, estas propiedades deshabilitarán todas las fechas en la ventana emergente del calendario antes o después de los valores respectivos y evitarán que el usuario avance el calendario más allá del mes o año (según la vista actual) que contiene la fecha mínima o máxima. .

Consulte el siguiente marcado HTML.

<mat-form-field class="example-full-width">
  <input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

 Además, consulte el archivo mecanografiado relacionado con el marcado anterior.

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

/** @title Datepicker with min & max validation */
@Component({
  selector: 'datepicker-min-max-example',
  templateUrl: 'datepicker-min-max-example.html',
  styleUrls: ['datepicker-min-max-example.css'],
})
export class DatepickerMinMaxExample {
  minDate = new Date(2000, 0, 1);
  maxDate = new Date(2020, 0, 1);
}

La segunda forma de agregar la validación de fecha es usando la propiedad matDatepickerFilter de la entrada del selector de fecha.

Esta propiedad acepta una función de <D> => booleano (donde <D> es el tipo de fecha utilizado por el selector de fecha, consulte Elección de una implementación de fecha).

Un resultado verdadero indica que la fecha es válida y un resultado falso sugiere que no lo es.

Nuevamente, esto también deshabilitará las fechas en un calendario que no son válidas.

Sin embargo, una diferencia crítica entre usar matDatepickerFilter y usar min o max es que filtrar todas las fechas antes o después de cierto punto no evitará que un usuario avance un calendario más allá de ese punto.

Consulte el siguiente ejemplo de código. Vea primero el marcado HTML.

<mat-form-field class="example-full-width">
  <input matInput [matDatepickerFilter]="myFilter" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

 Ahora, vea el archivo TypeScript relacionado con el marcado anterior.

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

/** @title Datepicker with filter validation */
@Component({
  selector: 'datepicker-filter-example',
  templateUrl: 'datepicker-filter-example.html',
  styleUrls: ['datepicker-filter-example.css'],
})
export class DatepickerFilterExample {
  myFilter = (d: Date): boolean => {
    const day = d.getDay();
    // Prevent Saturday and Sunday from being selected.
    return day !== 0 && day !== 6;
  }
}

En este ejemplo, el usuario puede retroceder hasta 2005, pero todas las fechas anteriores no podrán seleccionarse. No podrán retroceder más en el calendario que 2000.

Si escriben manualmente una fecha antes del mínimo, después del máximo o filtrada, la entrada tendrá errores de validación.

Cada propiedad de validación tiene un error diferente que se puede verificar:

  1. Por ejemplo, el valor que viola una propiedad mínima tendrá el error matDatepickerMin.
  2. El valor que viola una propiedad máxima tendrá el error matDatepickerMax.
  3. El valor que viola una propiedad matDatepickerFilter tendrá el error matDatepickerFilter.

Entrada angular y eventos de cambio

Los eventos nativos (entrada) y (cambio) de la entrada solo activarán la interacción del usuario con el elemento de entrada; no se activarán cuando el usuario seleccione la fecha de la ventana emergente del calendario.

Por lo tanto, una entrada de selector de fecha también admite eventos (dateInput) y (dateChange), que se activan cuando un usuario interactúa con una entrada o la ventana emergente.

El evento (dateInput) se activará siempre que el valor cambie debido a que el usuario escribe o selecciona una fecha del calendario. Del mismo modo, el evento (dateChange) se activará cada vez que el usuario termine de escribir la entrada (en <input> blur) o cuando un usuario elija la fecha de un calendario.

Consulte el siguiente marcado HTML.

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Input & change events"
         (dateInput)="addEvent('input', $event)" (dateChange)="addEvent('change', $event)">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

<div class="example-events">
  <div *ngFor="let e of events">{{e}}</div>
</div>

 Ahora, vea el archivo mecanografiado relacionado con ese marcado.

import {Component} from '@angular/core';
import {MatDatepickerInputEvent} from '@angular/material/datepicker';

/** @title Datepicker input and change events */
@Component({
  selector: 'datepicker-events-example',
  templateUrl: 'datepicker-events-example.html',
  styleUrls: ['datepicker-events-example.css'],
})
export class DatepickerEventsExample {
  events: string[] = [];

  addEvent(type: string, event: MatDatepickerInputEvent) {
    this.events.push(`${type}: ${event.value}`);
  }
}

Deshabilitar partes de Angular Datepicker

Al igual que con cualquier <entrada> estándar, es posible deshabilitar la entrada del selector de fecha agregando la propiedad deshabilitada.

De forma predeterminada, <mat-datepicker> y <mat-datepicker-toggle> heredarán su estado deshabilitado de <input>, pero esto se puede anular configurando una propiedad deshabilitada en el selector de fecha o los elementos de alternancia.

Esto es muy útil si desea deshabilitar la entrada de texto pero permitir la selección a través del calendario o viceversa.

Consulte el siguiente marcado HTML.

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp1" placeholder="Completely disabled" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp1"></mat-datepicker-toggle>
    <mat-datepicker #dp1></mat-datepicker>
  </mat-form-field>
</p>

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp2" placeholder="Popup disabled">
    <mat-datepicker-toggle matSuffix [for]="dp2" disabled></mat-datepicker-toggle>
    <mat-datepicker #dp2></mat-datepicker>
  </mat-form-field>
</p>

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp3" placeholder="Input disabled" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp3"></mat-datepicker-toggle>
    <mat-datepicker #dp3 disabled="false"></mat-datepicker>
  </mat-form-field>
</p>

 Ahora, vea el archivo mecanografiado.

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

/** @title Disabled datepicker */
@Component({
  selector: 'datepicker-disabled-example',
  templateUrl: 'datepicker-disabled-example.html',
  styleUrls: ['datepicker-disabled-example.css'],
})
export class DatepickerDisabledExample {}

Eso es todo por este tutorial. 

Fuente: https://appdividend.com/2022/02/16/angular-datepicker/

#angular 

How To Use Datepicker In Angular for Beginners

Angular Datepicker is a built-in material component that allows us to enter the date through text input or by choosing the date from a calendar. Angular Material Datepicker allows users to enter the date through text input or by choosing the date from the calendar. The Material Datepicker comprises several components and directives that work together.

It is made up of various angular components and directives that work together. First, we need to install AngularWe are using Angular CLI to install the Angular.

1: Install the Angular CLI.

Type the following command.

npm install -g @angular/cli

Now, create the Angular project using the following command.

ng new datepicker

2: Install other libraries.

Go into the project and install the hammerjs using the following command.

npm install --save hammerjs

Hammer.js is the optional dependency and helps with touch support for a few components.

Now, install Angular Material and Angular Animations using the following command.

npm install --save @angular/material @angular/animations @angular/cdk

Now, include hammerjs inside the angular.json file. You can find this file at the root of the project.

3: Import a pre-built theme and Material icons.

Angular Material comes with some pre-built themes. These themes have set off the colors and basic styling.

The main available themes are indigo-pink, deeppurple-amber, purple-green, and pink-bluegrey.

To import the theme, you can add the following code to your global styles.css file. The file is inside the src folder.

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

You can also access the Material Design icons and use named icons with a <mat-icon> component.

If we want to import them to your project, we can add this to the head section of your project’s root index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Datepicker</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
  <app-root></app-root>
</body>
</html>

4: Create a Custom Material Module File.

Inside the src,>> app folder, create one file called material.module.ts and add the following code.

// material.module.ts

import { NgModule } from '@angular/core';
import { MatDatepickerModule } from '@angular/material';

@NgModule({
  imports: [
    MatDatepickerModule
  ],
  exports: [
    MatDatepickerModule
  ]
})

export class MaterialModule {}

We have imported MatDatepickerModule, MatNativeDateModule, and other components that we need in our Angular Datepicker Example App.

We can add additional components in the future if we need to.

This file is written on its own because it is easy to include all the Material components in this file, and then this file will be imported inside the app.module.ts.

// material.module.ts

import { NgModule } from '@angular/core';
import { MatDatepickerModule,
        MatNativeDateModule,
        MatFormFieldModule,
        MatInputModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [
    MatDatepickerModule,
    MatFormFieldModule,
    MatNativeDateModule,
    MatInputModule,
    BrowserAnimationsModule
  ],
  exports: [
    MatDatepickerModule,
    MatFormFieldModule,
    MatNativeDateModule,
    MatInputModule,
    BrowserAnimationsModule
  ],
  providers: [ MatDatepickerModule ],
})

export class MaterialModule {}

5: Import MaterialModule in an app.module.ts file.

Import MaterialModule inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { MaterialModule } from './material.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MaterialModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Also, finally, write the Datepicker HTML code inside the app.component.html file.

<!-- app.component.html -->

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

Save the file, go to a terminal or cmd, and start Angular Development Server.

ng serve --open

Angular Datepicker Example | How To Use Datepicker In Angular

Go to the browser, and see something like the below image.

Angular 6 Datepicker Example Tutorial

6: Connecting a datepicker to an input

A datepicker comprises text input and a calendar popup, connected via the matDatePicker property on the text input.

<input [matDatepicker]="myDatepicker">
<mat-datepicker #myDatepicker></mat-datepicker>

There is an optional datepicker toggle button available. The toggle button can be added to the example above:

<input [matDatepicker]="myDatepicker">
<mat-datepicker-toggle [for]="myDatepicker"></mat-datepicker-toggle>
<mat-datepicker #myDatepicker></mat-datepicker>

It works the same with an input that is part of a <mat-form-field> and a toggle button can easily be used as a prefix or suffix on the material input:

<mat-form-field>
  <input matInput [matDatepicker]="myDatepicker">
  <mat-datepicker-toggle matSuffix [for]="myDatepicker"></mat-datepicker-toggle>
  <mat-datepicker #myDatepicker></mat-datepicker>
</mat-form-field>

7: Setting the calendar starting view

The startView property of <mat-datepicker> could be used to set the look that will show up when the calendar first opens. It can be configured to month, year, or multi-year; by default, it will begin to month view.

A month, year, or range of years that a calendar opens to is determined by first checking if any date is currently selected, and if so, it will open to a month or year containing that date. Otherwise, it will open in a month or year, providing today’s date.

This behavior can be easily overridden using the startAt property of <mat-datepicker>. In this case, a calendar will open to the month or year containing the startAt date.

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker startView="year" [startAt]="startDate"></mat-datepicker>
</mat-form-field>

Angular Material Datepicker Example Tutorial

You can find the code on Github.

Angular Datepicker Validation

Three properties add the date validation to the datepicker input.

The first two are the min and max properties.

Also, to enforce validation on input, these properties will disable all the dates on the calendar popup before or after the respective values and prevent the user from advancing the calendar past the month or year (depending on current view) containing the min or max date.

See the following HTML markup.

<mat-form-field class="example-full-width">
  <input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

 Also, see the typescript file related to the above markup.

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

/** @title Datepicker with min & max validation */
@Component({
  selector: 'datepicker-min-max-example',
  templateUrl: 'datepicker-min-max-example.html',
  styleUrls: ['datepicker-min-max-example.css'],
})
export class DatepickerMinMaxExample {
  minDate = new Date(2000, 0, 1);
  maxDate = new Date(2020, 0, 1);
}

The second way to add the date validation is by using the matDatepickerFilter property of the datepicker input.

This property accepts a function of <D> => boolean (where <D> is the date type used by the datepicker, see Choosing a date implementation).

A true result indicates that the date is valid, and a false result suggests that it is not.

Again this will also disable the dates on a calendar that are invalid.

However, a critical difference between using matDatepickerFilter vs. using min or max is that filtering out all dates before or after a certain point will not prevent a user from advancing a calendar past that point.

See the following code example. See first the HTML markup.

<mat-form-field class="example-full-width">
  <input matInput [matDatepickerFilter]="myFilter" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

 Now, see the Typescript file related to the above markup.

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

/** @title Datepicker with filter validation */
@Component({
  selector: 'datepicker-filter-example',
  templateUrl: 'datepicker-filter-example.html',
  styleUrls: ['datepicker-filter-example.css'],
})
export class DatepickerFilterExample {
  myFilter = (d: Date): boolean => {
    const day = d.getDay();
    // Prevent Saturday and Sunday from being selected.
    return day !== 0 && day !== 6;
  }
}

In this example, the user can go back past 2005, but all of the dates before then will be unselectable. They will not be able to go further back in the calendar than 2000.

If they manually type in a date before the min, after the max, or filtered out, the input will have validation errors.

Each validation property has a different error that can be checked:

  1. For example, the value that violates a min property will have the matDatepickerMin error.
  2. The value that violates a max property will have the matDatepickerMax error.
  3. The value that violates a matDatepickerFilter property will have the matDatepickerFilter error.

Angular Input and change events

The input’s native (input) and (change) events will only trigger user interaction with the input element; they will not fire when the user selects the date from the calendar popup.

Therefore, a datepicker input also has support for (dateInput) and (dateChange) events — these triggers when a user interacts with either an input or the popup.

The (dateInput) event will fire whenever the value changes due to the user typing or selecting a date from the calendar. Likewise, the (dateChange) event will fire whenever the user finishes typing input (on <input> blur) or when a user chooses the date from a calendar.

See the following HTML Markup.

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Input & change events"
         (dateInput)="addEvent('input', $event)" (dateChange)="addEvent('change', $event)">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

<div class="example-events">
  <div *ngFor="let e of events">{{e}}</div>
</div>

 Now, see the typescript file related to that markup.

import {Component} from '@angular/core';
import {MatDatepickerInputEvent} from '@angular/material/datepicker';

/** @title Datepicker input and change events */
@Component({
  selector: 'datepicker-events-example',
  templateUrl: 'datepicker-events-example.html',
  styleUrls: ['datepicker-events-example.css'],
})
export class DatepickerEventsExample {
  events: string[] = [];

  addEvent(type: string, event: MatDatepickerInputEvent) {
    this.events.push(`${type}: ${event.value}`);
  }
}

Disabling parts of the Angular Datepicker

As with any standard <input>, it is possible to disable the datepicker input by adding the disabled property.

By default, the <mat-datepicker> and <mat-datepicker-toggle> will inherit their disabled state from the <input>, but this can be overridden by setting a disabled property on the datepicker or toggle elements.

This is very useful if you want to disable the text input but allow selection via the calendar or vice-versa.

See the following HTML Markup.

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp1" placeholder="Completely disabled" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp1"></mat-datepicker-toggle>
    <mat-datepicker #dp1></mat-datepicker>
  </mat-form-field>
</p>

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp2" placeholder="Popup disabled">
    <mat-datepicker-toggle matSuffix [for]="dp2" disabled></mat-datepicker-toggle>
    <mat-datepicker #dp2></mat-datepicker>
  </mat-form-field>
</p>

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp3" placeholder="Input disabled" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp3"></mat-datepicker-toggle>
    <mat-datepicker #dp3 disabled="false"></mat-datepicker>
  </mat-form-field>
</p>

 Now, see the typescript file.

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

/** @title Disabled datepicker */
@Component({
  selector: 'datepicker-disabled-example',
  templateUrl: 'datepicker-disabled-example.html',
  styleUrls: ['datepicker-disabled-example.css'],
})
export class DatepickerDisabledExample {}

That’s it for this tutorial.

Angular Datepicker: How to use Datepicker in Angular 13

Angular Material is ground running with significant, modern UI components that work across the web, mobile, and desktop

Angular Material components will help us construct attractive UI and UX, consistent and functional web pages, and web applications while keeping to modern web design principles like browser portability and compatibility, device independence, and graceful degradation.

Angular Datepicker

Angular Datepicker is a built-in material component that allows us to enter the date through text input or by choosing the date from a calendar. Angular Material Datepicker allows users to enter the date through text input or by choosing the date from the calendar. The Material Datepicker comprises several components and directives that work together.

It is made up of various angular components and directives that work together. First, we need to install Angular. We are using Angular CLI to install the Angular.

Step 1: Install the Angular CLI.

Type the following command.

npm install -g @angular/cli

Now, create the Angular project using the following command.

 

ng new datepicker

Step 2: Install other libraries.

Go into the project and install the hammerjs using the following command.

npm install --save hammerjs

Hammer.js is the optional dependency and helps with touch support for a few components.

Now, install Angular Material and Angular Animations using the following command.

npm install --save @angular/material @angular/animations @angular/cdk

Now, include hammerjs inside the angular.json file. You can find this file at the root of the project.

Step 3: Import a pre-built theme and Material icons.

Angular Material comes with some pre-built themes. These themes have set off the colors and basic styling.

The main available themes are indigo-pinkdeeppurple-amberpurple-green, and pink-bluegrey.

To import the theme, you can add the following code to your global styles.css file. The file is inside the src folder.

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

You can also access the Material Design icons and use named icons with a <mat-icon> component.

If we want to import them to your project, we can add this to the head section of your project’s root index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Datepicker</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Step 4: Create a Custom Material Module File.

Inside the src,>> app folder, create one file called material.module.ts and add the following code.

// material.module.ts

import { NgModule } from '@angular/core';
import { MatDatepickerModule } from '@angular/material';

@NgModule({
  imports: [
    MatDatepickerModule
  ],
  exports: [
    MatDatepickerModule
  ]
})

export class MaterialModule {}

We have imported MatDatepickerModule, MatNativeDateModule, and other components that we need in our Angular Datepicker Example App.

We can add additional components in the future if we need to.

This file is written on its own because it is easy to include all the Material components in this file, and then this file will be imported inside the app.module.ts.

// material.module.ts

import { NgModule } from '@angular/core';
import { MatDatepickerModule,
        MatNativeDateModule,
        MatFormFieldModule,
        MatInputModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [
    MatDatepickerModule,
    MatFormFieldModule,
    MatNativeDateModule,
    MatInputModule,
    BrowserAnimationsModule
  ],
  exports: [
    MatDatepickerModule,
    MatFormFieldModule,
    MatNativeDateModule,
    MatInputModule,
    BrowserAnimationsModule
  ],
  providers: [ MatDatepickerModule ],
})

export class MaterialModule {}

Step 5: Import MaterialModule in an app.module.ts file.

Import MaterialModule inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { MaterialModule } from './material.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MaterialModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Also, finally, write the Datepicker HTML code inside the app.component.html file.

<!-- app.component.html -->

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

Save the file, go to a terminal or cmd, and start Angular Development Server.

ng serve --open

Angular Datepicker Example | How To Use Datepicker In Angular

Go to the browser, and see something like the below image.

Angular 6 Datepicker Example TutorialStep 6: Connecting a datepicker to an input

A datepicker comprises text input and a calendar popup, connected via the matDatePicker property on the text input.

<input [matDatepicker]="myDatepicker">
<mat-datepicker #myDatepicker></mat-datepicker>

There is an optional datepicker toggle button available. The toggle button can be added to the example above:

<input [matDatepicker]="myDatepicker">
<mat-datepicker-toggle [for]="myDatepicker"></mat-datepicker-toggle>
<mat-datepicker #myDatepicker></mat-datepicker>

It works the same with an input that is part of a <mat-form-field> and a toggle button can easily be used as a prefix or suffix on the material input:

<mat-form-field>
  <input matInput [matDatepicker]="myDatepicker">
  <mat-datepicker-toggle matSuffix [for]="myDatepicker"></mat-datepicker-toggle>
  <mat-datepicker #myDatepicker></mat-datepicker>
</mat-form-field>

Step 7: Setting the calendar starting view

The startView property of <mat-datepicker> could be used to set the look that will show up when the calendar first opens. It can be configured to monthyear, or multi-year; by default, it will begin to month view.

A month, year, or range of years that a calendar opens to is determined by first checking if any date is currently selected, and if so, it will open to a month or year containing that date. Otherwise, it will open in a month or year, providing today’s date.

This behavior can be easily overridden using the startAt property of <mat-datepicker>. In this case, a calendar will open to the month or year containing the startAt date.

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker startView="year" [startAt]="startDate"></mat-datepicker>
</mat-form-field>

Angular Material Datepicker Example Tutorial

You can find the code on Github.

GITHUB CODE

Angular Datepicker Validation

Three properties add the date validation to the datepicker input.

The first two are the min and max properties.

Also, to enforce validation on input, these properties will disable all the dates on the calendar popup before or after the respective values and prevent the user from advancing the calendar past the month or year (depending on current view) containing the min or max date.

See the following HTML markup.

<mat-form-field class="example-full-width">
  <input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

 Also, see the typescript file related to the above markup.

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

/** @title Datepicker with min & max validation */
@Component({
  selector: 'datepicker-min-max-example',
  templateUrl: 'datepicker-min-max-example.html',
  styleUrls: ['datepicker-min-max-example.css'],
})
export class DatepickerMinMaxExample {
  minDate = new Date(2000, 0, 1);
  maxDate = new Date(2020, 0, 1);
}

The second way to add the date validation is by using the matDatepickerFilter property of the datepicker input.

This property accepts a function of <D> => boolean (where <D> is the date type used by the datepicker, see Choosing a date implementation).

A true result indicates that the date is valid, and a false result suggests that it is not.

Again this will also disable the dates on a calendar that are invalid.

However, a critical difference between using matDatepickerFilter vs. using min or max is that filtering out all dates before or after a certain point will not prevent a user from advancing a calendar past that point.

See the following code example. See first the HTML markup.

<mat-form-field class="example-full-width">
  <input matInput [matDatepickerFilter]="myFilter" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

 Now, see the Typescript file related to the above markup.

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

/** @title Datepicker with filter validation */
@Component({
  selector: 'datepicker-filter-example',
  templateUrl: 'datepicker-filter-example.html',
  styleUrls: ['datepicker-filter-example.css'],
})
export class DatepickerFilterExample {
  myFilter = (d: Date): boolean => {
    const day = d.getDay();
    // Prevent Saturday and Sunday from being selected.
    return day !== 0 && day !== 6;
  }
}

In this example, the user can go back past 2005, but all of the dates before then will be unselectable. They will not be able to go further back in the calendar than 2000.

If they manually type in a date before the min, after the max, or filtered out, the input will have validation errors.

Each validation property has a different error that can be checked:

  1. For example, the value that violates a min property will have the matDatepickerMin error.
  2. The value that violates a max property will have the matDatepickerMax error.
  3. The value that violates a matDatepickerFilter property will have the matDatepickerFilter error.

Angular Input and change events

The input’s native (input) and (change) events will only trigger user interaction with the input element; they will not fire when the user selects the date from the calendar popup.

Therefore, a datepicker input also has support for (dateInput) and (dateChange) events — these triggers when a user interacts with either an input or the popup.

The (dateInput) event will fire whenever the value changes due to the user typing or selecting a date from the calendar. Likewise, the (dateChange) event will fire whenever the user finishes typing input (on <input> blur) or when a user chooses the date from a calendar.

See the following HTML Markup.

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Input & change events"
         (dateInput)="addEvent('input', $event)" (dateChange)="addEvent('change', $event)">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

<div class="example-events">
  <div *ngFor="let e of events">{{e}}</div>
</div>

 Now, see the typescript file related to that markup.

import {Component} from '@angular/core';
import {MatDatepickerInputEvent} from '@angular/material/datepicker';

/** @title Datepicker input and change events */
@Component({
  selector: 'datepicker-events-example',
  templateUrl: 'datepicker-events-example.html',
  styleUrls: ['datepicker-events-example.css'],
})
export class DatepickerEventsExample {
  events: string[] = [];

  addEvent(type: string, event: MatDatepickerInputEvent) {
    this.events.push(`${type}: ${event.value}`);
  }
}

Disabling parts of the Angular Datepicker

As with any standard <input>, it is possible to disable the datepicker input by adding the disabled property.

By default, the <mat-datepicker> and <mat-datepicker-toggle> will inherit their disabled state from the <input>, but this can be overridden by setting a disabled property on the datepicker or toggle elements.

This is very useful if you want to disable the text input but allow selection via the calendar or vice-versa.

See the following HTML Markup.

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp1" placeholder="Completely disabled" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp1"></mat-datepicker-toggle>
    <mat-datepicker #dp1></mat-datepicker>
  </mat-form-field>
</p>

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp2" placeholder="Popup disabled">
    <mat-datepicker-toggle matSuffix [for]="dp2" disabled></mat-datepicker-toggle>
    <mat-datepicker #dp2></mat-datepicker>
  </mat-form-field>
</p>

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp3" placeholder="Input disabled" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp3"></mat-datepicker-toggle>
    <mat-datepicker #dp3 disabled="false"></mat-datepicker>
  </mat-form-field>
</p>

 Now, see the typescript file.

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

/** @title Disabled datepicker */
@Component({
  selector: 'datepicker-disabled-example',
  templateUrl: 'datepicker-disabled-example.html',
  styleUrls: ['datepicker-disabled-example.css'],
})
export class DatepickerDisabledExample {}

That’s it for this tutorial. 

Source: https://appdividend.com/2022/02/16/angular-datepicker/

#angular