1582786320
@adrianjost/two-channel-picker. A simple two channel Color Picker
I needed an intuitive color picker to control my warm-white-cold-white (WWCW) LED Strips with the SmartLight Project.
The picker value is therefore indepent from the displayed color. The given value is a number between 0 and 1 for each of the two channels. The brightness can be determined by dragging the slider along the Y-axis. Dragging along the X-axis changes the relationship between the two channels.
<script src="https://cdn.jsdelivr.net/npm/@adrianjost/two-channel-picker@0.3.1/dist/wc/two-channel-picker.min.js"></script>
<div style="width: 300px; height: 300px;">
<two-channel-picker
value="[0,1]"
id="picker"
options='{"colorLeft": "#f00", "colorRight": "#00f" }'
></two-channel-picker>
</div>
<script>
document.getElementById("picker").addEventListener("input", (event) => {
console.log(event.detail[0]);
});
</script>
please note, that you may need to adjust the version number in the url.
Install the package:
npm i @adrianjost/two-channel-picker
or
yarn add @adrianjost/two-channel-picker
In your App:
<template>
<TwoChannelPicker
v-model="channels"
:options="{
colorLeft: '#fd9',
colorRight: '#9df',
marker: {
radius: 16,
borderWidth: 2,
},
}"
/>
</template>
<script>
import TwoChannelPicker from "@adrianjost/two-channel-picker";
export default {
components: {
TwoChannelPicker,
},
data() {
return {
channels: [0, 1],
};
},
};
</script>
The package also includes some helper methods. You can access them by importing the according js files. Please use the JSDoc comments to learn how to use them.
import {
getChannelsForHueAndBrightness,
getHueAndBrightnessForChannels,
getCenterColor,
getColorForHueAndBrightness,
getColorForChannels,
} from "@adrianjost/two-channel-picker/dist/helpers/channelColor.js";
import {
hex2rgb,
rgb2hex,
} from "@adrianjost/two-channel-picker/dist/helpers/colorConversion.js";
You can customize the picker with the following props/attributes.
When using the lib as a web component you must provide all attributes
JSON.stringify()
-ed.
attribute | type | default value | description |
---|---|---|---|
value / v-model |
Array, String | [1,0] |
the current channel values, if provided as a String, this must be JSON.parse() -able |
options |
Object | {} |
all your config goes in here |
Available Attributes in the options
prop:
attribute | type | default value | description |
---|---|---|---|
readOnly |
Boolean | false |
should the user be able to move the marker? |
colorLeft |
String | #fd9 |
the color in the top left corner. Must be in the HEX Format with 3 or 6 digits. |
colorRight |
String | #fd9 |
the color in the top right corner. Must be in the HEX Format with 3 or 6 digits. |
marker.borderWidth |
Number | 2 |
The border width of the active marker in px. |
marker.radius |
Number | 16 |
The border radius including the borderWidth in px. |
You need more options? Please open an issue and I will do my best to implement it. Pull Requests are also welcome!
Author: adrianjost
Live Demo:
GitHub: https://github.com/adrianjost/two-channel-picker
#vuejs #javascript #vue-js
1679035563
When your app is opened, there is a brief time while the native app loads Flutter. By default, during this time, the native app displays a white splash screen. This package automatically generates iOS, Android, and Web-native code for customizing this native splash screen background color and splash image. Supports dark mode, full screen, and platform-specific options.
[BETA] Support for flavors is in beta. Currently only Android and iOS are supported. See instructions below.
You can now keep the splash screen up while your app initializes! No need for a secondary splash screen anymore. Just use the preserve
and remove
methods together to remove the splash screen after your initialization is complete. See details below.
Would you prefer a video tutorial instead? Check out Johannes Milke's tutorial.
First, add flutter_native_splash
as a dependency in your pubspec.yaml file.
dependencies:
flutter_native_splash: ^2.2.19
Don't forget to flutter pub get
.
Customize the following settings and add to your project's pubspec.yaml
file or place in a new file in your root project folder named flutter_native_splash.yaml
.
flutter_native_splash:
# This package generates native code to customize Flutter's default white native splash screen
# with background color and splash image.
# Customize the parameters below, and run the following command in the terminal:
# flutter pub run flutter_native_splash:create
# To restore Flutter's default white splash screen, run the following command in the terminal:
# flutter pub run flutter_native_splash:remove
# color or background_image is the only required parameter. Use color to set the background
# of your splash screen to a solid color. Use background_image to set the background of your
# splash screen to a png image. This is useful for gradients. The image will be stretch to the
# size of the app. Only one parameter can be used, color and background_image cannot both be set.
color: "#42a5f5"
#background_image: "assets/background.png"
# Optional parameters are listed below. To enable a parameter, uncomment the line by removing
# the leading # character.
# The image parameter allows you to specify an image used in the splash screen. It must be a
# png file and should be sized for 4x pixel density.
#image: assets/splash.png
# The branding property allows you to specify an image used as branding in the splash screen.
# It must be a png file. It is supported for Android, iOS and the Web. For Android 12,
# see the Android 12 section below.
#branding: assets/dart.png
# To position the branding image at the bottom of the screen you can use bottom, bottomRight,
# and bottomLeft. The default values is bottom if not specified or specified something else.
#branding_mode: bottom
# The color_dark, background_image_dark, image_dark, branding_dark are parameters that set the background
# and image when the device is in dark mode. If they are not specified, the app will use the
# parameters from above. If the image_dark parameter is specified, color_dark or
# background_image_dark must be specified. color_dark and background_image_dark cannot both be
# set.
#color_dark: "#042a49"
#background_image_dark: "assets/dark-background.png"
#image_dark: assets/splash-invert.png
#branding_dark: assets/dart_dark.png
# Android 12 handles the splash screen differently than previous versions. Please visit
# https://developer.android.com/guide/topics/ui/splash-screen
# Following are Android 12 specific parameter.
android_12:
# The image parameter sets the splash screen icon image. If this parameter is not specified,
# the app's launcher icon will be used instead.
# Please note that the splash screen will be clipped to a circle on the center of the screen.
# App icon with an icon background: This should be 960×960 pixels, and fit within a circle
# 640 pixels in diameter.
# App icon without an icon background: This should be 1152×1152 pixels, and fit within a circle
# 768 pixels in diameter.
#image: assets/android12splash.png
# Splash screen background color.
#color: "#42a5f5"
# App icon background color.
#icon_background_color: "#111111"
# The branding property allows you to specify an image used as branding in the splash screen.
#branding: assets/dart.png
# The image_dark, color_dark, icon_background_color_dark, and branding_dark set values that
# apply when the device is in dark mode. If they are not specified, the app will use the
# parameters from above.
#image_dark: assets/android12splash-invert.png
#color_dark: "#042a49"
#icon_background_color_dark: "#eeeeee"
# The android, ios and web parameters can be used to disable generating a splash screen on a given
# platform.
#android: false
#ios: false
#web: false
# Platform specific images can be specified with the following parameters, which will override
# the respective parameter. You may specify all, selected, or none of these parameters:
#color_android: "#42a5f5"
#color_dark_android: "#042a49"
#color_ios: "#42a5f5"
#color_dark_ios: "#042a49"
#color_web: "#42a5f5"
#color_dark_web: "#042a49"
#image_android: assets/splash-android.png
#image_dark_android: assets/splash-invert-android.png
#image_ios: assets/splash-ios.png
#image_dark_ios: assets/splash-invert-ios.png
#image_web: assets/splash-web.png
#image_dark_web: assets/splash-invert-web.png
#background_image_android: "assets/background-android.png"
#background_image_dark_android: "assets/dark-background-android.png"
#background_image_ios: "assets/background-ios.png"
#background_image_dark_ios: "assets/dark-background-ios.png"
#background_image_web: "assets/background-web.png"
#background_image_dark_web: "assets/dark-background-web.png"
#branding_android: assets/brand-android.png
#branding_dark_android: assets/dart_dark-android.png
#branding_ios: assets/brand-ios.png
#branding_dark_ios: assets/dart_dark-ios.png
# The position of the splash image can be set with android_gravity, ios_content_mode, and
# web_image_mode parameters. All default to center.
#
# android_gravity can be one of the following Android Gravity (see
# https://developer.android.com/reference/android/view/Gravity): bottom, center,
# center_horizontal, center_vertical, clip_horizontal, clip_vertical, end, fill, fill_horizontal,
# fill_vertical, left, right, start, or top.
#android_gravity: center
#
# ios_content_mode can be one of the following iOS UIView.ContentMode (see
# https://developer.apple.com/documentation/uikit/uiview/contentmode): scaleToFill,
# scaleAspectFit, scaleAspectFill, center, top, bottom, left, right, topLeft, topRight,
# bottomLeft, or bottomRight.
#ios_content_mode: center
#
# web_image_mode can be one of the following modes: center, contain, stretch, and cover.
#web_image_mode: center
# The screen orientation can be set in Android with the android_screen_orientation parameter.
# Valid parameters can be found here:
# https://developer.android.com/guide/topics/manifest/activity-element#screen
#android_screen_orientation: sensorLandscape
# To hide the notification bar, use the fullscreen parameter. Has no effect in web since web
# has no notification bar. Defaults to false.
# NOTE: Unlike Android, iOS will not automatically show the notification bar when the app loads.
# To show the notification bar, add the following code to your Flutter app:
# WidgetsFlutterBinding.ensureInitialized();
# SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom, SystemUiOverlay.top]);
#fullscreen: true
# If you have changed the name(s) of your info.plist file(s), you can specify the filename(s)
# with the info_plist_files parameter. Remove only the # characters in the three lines below,
# do not remove any spaces:
#info_plist_files:
# - 'ios/Runner/Info-Debug.plist'
# - 'ios/Runner/Info-Release.plist'
After adding your settings, run the following command in the terminal:
flutter pub run flutter_native_splash:create
When the package finishes running, your splash screen is ready.
To specify the YAML file location just add --path with the command in the terminal:
flutter pub run flutter_native_splash:create --path=path/to/my/file.yaml
By default, the splash screen will be removed when Flutter has drawn the first frame. If you would like the splash screen to remain while your app initializes, you can use the preserve()
and remove()
methods together. Pass the preserve()
method the value returned from WidgetsFlutterBinding.ensureInitialized()
to keep the splash on screen. Later, when your app has initialized, make a call to remove()
to remove the splash screen.
import 'package:flutter_native_splash/flutter_native_splash.dart';
void main() {
WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
runApp(const MyApp());
}
// whenever your initialization is completed, remove the splash screen:
FlutterNativeSplash.remove();
NOTE: If you do not need to use the preserve()
and remove()
methods, you can place the flutter_native_splash
dependency in the dev_dependencies
section of pubspec.yaml
.
If you find this package useful, you can support it for free by giving it a thumbs up at the top of this page. Here's another option to support the package:
Android 12 has a new method of adding splash screens, which consists of a window background, icon, and the icon background. Note that a background image is not supported.
Be aware of the following considerations regarding these elements:
1: image
parameter. By default, the launcher icon is used:
2: icon_background_color
is optional, and is useful if you need more contrast between the icon and the window background.
3: One-third of the foreground is masked.
4: color
the window background consists of a single opaque color.
PLEASE NOTE: The splash screen may not appear when you launch the app from Android Studio on API 31. However, it should appear when you launch by clicking on the launch icon in Android. This seems to be resolved in API 32+.
PLEASE NOTE: There are a number of reports that non-Google launchers do not display the launch image correctly. If the launch image does not display correctly, please try the Google launcher to confirm that this package is working.
PLEASE NOTE: The splash screen does not appear when you launch the app from a notification. Apparently this is the intended behavior on Android 12: core-splashscreen Icon not shown when cold launched from notification.
If you have a project setup that contains multiple flavors or environments, and you created more than one flavor this would be a feature for you.
Instead of maintaining multiple files and copy/pasting images, you can now, using this tool, create different splash screens for different environments.
In order to use the new feature, and generate the desired splash images for you app, a couple of changes are required.
If you want to generate just one flavor and one file you would use either options as described in Step 1. But in order to setup the flavors, you will then be required to move all your setup values to the flutter_native_splash.yaml
file, but with a prefix.
Let's assume for the rest of the setup that you have 3 different flavors, Production
, Acceptance
, Development
.
First this you will need to do is to create a different setup file for all 3 flavors with a suffix like so:
flutter_native_splash-production.yaml
flutter_native_splash-acceptance.yaml
flutter_native_splash-development.yaml
You would setup those 3 files the same way as you would the one, but with different assets depending on which environment you would be generating. For example (Note: these are just examples, you can use whatever setup you need for your project that is already supported by the package):
# flutter_native_splash-development.yaml
flutter_native_splash:
color: "#ffffff"
image: assets/logo-development.png
branding: assets/branding-development.png
color_dark: "#121212"
image_dark: assets/logo-development.png
branding_dark: assets/branding-development.png
android_12:
image: assets/logo-development.png
icon_background_color: "#ffffff"
image_dark: assets/logo-development.png
icon_background_color_dark: "#121212"
web: false
# flutter_native_splash-acceptance.yaml
flutter_native_splash:
color: "#ffffff"
image: assets/logo-acceptance.png
branding: assets/branding-acceptance.png
color_dark: "#121212"
image_dark: assets/logo-acceptance.png
branding_dark: assets/branding-acceptance.png
android_12:
image: assets/logo-acceptance.png
icon_background_color: "#ffffff"
image_dark: assets/logo-acceptance.png
icon_background_color_dark: "#121212"
web: false
# flutter_native_splash-production.yaml
flutter_native_splash:
color: "#ffffff"
image: assets/logo-production.png
branding: assets/branding-production.png
color_dark: "#121212"
image_dark: assets/logo-production.png
branding_dark: assets/branding-production.png
android_12:
image: assets/logo-production.png
icon_background_color: "#ffffff"
image_dark: assets/logo-production.png
icon_background_color_dark: "#121212"
web: false
Great, now comes the fun part running the new command!
The new command is:
# If you have a flavor called production you would do this:
flutter pub run flutter_native_splash:create --flavor production
# For a flavor with a name staging you would provide it's name like so:
flutter pub run flutter_native_splash:create --flavor staging
# And if you have a local version for devs you could do that:
flutter pub run flutter_native_splash:create --flavor development
You're done! No, really, Android doesn't need any additional setup.
Note: If it didn't work, please make sure that your flavors are named the same as your config files, otherwise the setup will not work.
iOS is a bit tricky, so hang tight, it might look scary but most of the steps are just a single click, explained as much as possible to lower the possibility of mistakes.
When you run the new command, you will need to open xCode and follow the steps bellow:
Assumption
schemes
setup; production, acceptance and development.Preparation
{project root}/ios/Runner/Base.lproj
xCode
Xcode still doesn't know how to use them, so we need to specify for all the current flavors (schemes) which file to use and to use that value inside the Info.plist file.
LAUNCH_SCREEN_STORYBOARD
$(LAUNCH_SCREEN_STORYBOARD)
Congrats you finished your setup for multiple flavors,
This message is not related to this package but is related to a change in how Flutter handles splash screens in Flutter 2.5. It is caused by having the following code in your android/app/src/main/AndroidManifest.xml
, which was included by default in previous versions of Flutter:
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
The solution is to remove the above code. Note that this will also remove the fade effect between the native splash screen and your app.
Not at this time. PRs are always welcome!
This attribute is only found in Android 12, so if you are getting this error, it means your project is not fully set up for Android 12. Did you update your app's build configuration?
This is caused by an iOS splash caching bug, which can be solved by uninstalling your app, powering off your device, power back on, and then try reinstalling.
removeAfter
method.No. This package creates a splash screen that is displayed before Flutter is loaded. Because of this, when the splash screen loads, internal app settings are not available to the splash screen. Unfortunately, this means that it is impossible to control light/dark settings of the splash from app settings.
Notes
If the splash screen was not updated correctly on iOS or if you experience a white screen before the splash screen, run flutter clean
and recompile your app. If that does not solve the problem, delete your app, power down the device, power up the device, install and launch the app as per this StackOverflow thread.
This package modifies launch_background.xml
and styles.xml
files on Android, LaunchScreen.storyboard
and Info.plist
on iOS, and index.html
on Web. If you have modified these files manually, this plugin may not work properly. Please open an issue if you find any bugs.
mdpi
, hdpi
, xhdpi
, xxhdpi
and xxxhdpi
drawables.<item>
tag containing a <bitmap>
for your splash image drawable will be added in launch_background.xml
colors.xml
and referenced in launch_background.xml
.styles.xml
.drawable-night
, values-night
, etc. resource folders.@3x
and @2x
images.LaunchScreen.storyboard
.Info.plist
.web/splash
folder will be created for splash screen images and CSS files.1x
, 2x
, 3x
, and 4x
sizes and placed in web/splash/img
.web/index.html
, as well as the HTML for the splash pictures.This package was originally created by Henrique Arthur and it is currently maintained by Jon Hanson.
If you encounter any problems feel free to open an issue. If you feel the library is missing a feature, please raise a ticket. Pull request are also welcome.
Run this command:
With Flutter:
$ flutter pub add flutter_native_splash
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
flutter_native_splash: ^2.2.19
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
void main() {
WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
void initState() {
super.initState();
initialization();
}
void initialization() async {
// This is where you can initialize the resources needed by your app while
// the splash screen is displayed. Remove the following example because
// delaying the user experience is a bad design practice!
// ignore_for_file: avoid_print
print('ready in 3...');
await Future.delayed(const Duration(seconds: 1));
print('ready in 2...');
await Future.delayed(const Duration(seconds: 1));
print('ready in 1...');
await Future.delayed(const Duration(seconds: 1));
print('go!');
FlutterNativeSplash.remove();
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Author: jonbhanson
Download Link: Download The Source Code
Official Website: https://github.com/jonbhanson/flutter_native_splash
License: MIT license
1600583123
In this article, we are going to list out the most popular websites using Vue JS as their frontend framework.
Vue JS is one of those elite progressive JavaScript frameworks that has huge demand in the web development industry. Many popular websites are developed using Vue in their frontend development because of its imperative features.
This framework was created by Evan You and still it is maintained by his private team members. Vue is of course an open-source framework which is based on MVVM concept (Model-view view-Model) and used extensively in building sublime user-interfaces and also considered a prime choice for developing single-page heavy applications.
Released in February 2014, Vue JS has gained 64,828 stars on Github, making it very popular in recent times.
Evan used Angular JS on many operations while working for Google and integrated many features in Vue to cover the flaws of Angular.
“I figured, what if I could just extract the part that I really liked about Angular and build something really lightweight." - Evan You
#vuejs #vue #vue-with-laravel #vue-top-story #vue-3 #build-vue-frontend #vue-in-laravel #vue.js
1648564858
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.
Type the following command.
npm install -g @angular/cli
Now, create the Angular project using the following command.
ng new datepicker
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.
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>
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 {}
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
Go to the browser, and see something like the below image.
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>
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>
You can find the code on Github.
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:
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}`);
}
}
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.
1650810840
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.
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.
Escriba el siguiente comando.
npm install -g @angular/cli
Ahora, crea el proyecto Angular usando el siguiente comando.
ng new datepicker
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 y 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.
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>
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 {}
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
Vaya al navegador y vea algo como la imagen de abajo.
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>
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 mes , año o varios 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>
Puedes encontrar el código en Github.
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:
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}`);
}
}
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/
1650785100
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 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.
Type the following command.
npm install -g @angular/cli
Now, create the Angular project using the following command.
ng new datepicker
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.
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>
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 {}
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
Go to the browser, and see something like the below image.
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>
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>
You can find the code on Github.
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:
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}`);
}
}
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/