Descripción general del componente Selector de rango de fechas Angular
El selector de intervalo de fechas Angular es un componente ligero que incluye una entrada de texto y una ventana emergente de calendario, lo que permite a los usuarios seleccionar fácilmente las fechas de inicio y finalización. Es altamente personalizable para adaptarse a varios requisitos de la aplicación, ofreciendo características como restricciones de rango de fechas, formatos de fecha configurables y más.
Angular Date Range Picker Example
A continuación se muestra un ejemplo que muestra elIgxDateRangePickerComponent componente en acción, donde una ventana emergente en el calendario permite a los usuarios seleccionar fechas de inicio y finalización.
Getting Started with Ignite UI for Angular Date Range Picker
To get started with the Ignite UI for Angular IgxDateRangePickerComponent component, first you need to install Ignite UI for Angular. In an existing Angular application, type the following command:
ng add igniteui-angular
Para obtener una introducción completa al Ignite UI for Angular, lea el tema de introducción.
El siguiente paso es importarlosIgxDateRangePickerModule en tu archivo app.module.ts.
As the IgxDateRangePickerComponent uses the IgxCalendarComponent, it also has a dependency on the BrowserAnimationsModule and optionally the HammerModule for touch interactions, so they need to be added to the AppModule as well:
// app.module.ts
import { IgxDateRangePickerModule } from 'igniteui-angular/date-picker';
// import { IgxDateRangePickerModule } from '@infragistics/igniteui-angular'; for licensed package
import { HammerModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
...
imports: [..., IgxDateRangePickerModule, BrowserAnimationsModule, HammerModule],
...
})
export class AppModule {}
Alternatively, as of 16.0.0 you can import the IgxDateRangePickerComponent as a standalone dependency, or use the IGX_DATE_RANGE_PICKER_DIRECTIVES token to import the component and all of its supporting components and directives.
// home.component.ts
import { HammerModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { IGX_DATE_RANGE_PICKER_DIRECTIVES } from 'igniteui-angular/date-picker';
// import { IGX_DATE_RANGE_PICKER_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
@Component({
selector: 'app-home',
template: '<igx-date-range-picker [value]="range"></igx-date-range-picker>',
styleUrls: ['home.component.scss'],
standalone: true,
imports: [BrowserAnimationsModule, HammerModule, IGX_DATE_RANGE_PICKER_DIRECTIVES]
/* or imports: [BrowserAnimationsModule, HammerModule, IgxDateRangePickerComponent] */
})
export class HomeComponent {}
Now that you have the Ignite UI for Angular Date Range Picker module or directives imported, you can start using the igx-date-range-picker component.
Using the Angular Date Range Picker Component
Display and Value
Para crear una instancia de un selector de rango de fechas en su modo predeterminado, use el siguiente código:
<igx-date-range-picker [value]="range"></igx-date-range-picker>
public range: DateRange = { start: new Date(2020, 4, 20), end: new Date(2020, 4, 25) };
Note
The Date Range Picker value is of type DateRange, which contains a start and an end date.
El selector ofrece dos modos para mostrar los valores de fecha: entrada única y dos entradas. En el modo de entrada única, el campo no se puede editar y el intervalo de fechas no se puede editar escribiendo. Sin embargo, en el modo de dos entradas, los usuarios pueden editar las fechas de inicio y finalización escribiendo campos de entrada separados.
Cuando el calendario está visible, se puede seleccionar un intervalo de fechas eligiendo una fecha de inicio y una de finalización. Al seleccionar una fecha, se establecerá tanto la fecha de inicio como la de finalización y, una vez que se elija una segunda fecha, se establecerá la fecha de finalización. Si ya se ha seleccionado un intervalo, al hacer clic en cualquier otra fecha del calendario se iniciará una nueva selección de intervalo.
To create a two-way data-binding, use ngModel:
<igx-date-range-picker [(ngModel)]="range"></igx-date-range-picker>
Display Separate Editable Inputs
The Angular Date Range Picker component also allows configuring two separate inputs for start and end date. This can be achieved by using the IgxDateRangeStartComponent and IgxDateRangeEndComponent as children of the date range picker, as shown in the demo below:
<igx-date-range-picker [(ngModel)]="range">
<igx-date-range-start>
<input igxInput igxDateTimeEditor type="text">
</igx-date-range-start>
<igx-date-range-end>
<input igxInput igxDateTimeEditor type="text">
</igx-date-range-end>
</igx-date-range-picker>
- Both the
IgxDateRangeStartComponentandIgxDateRangeEndComponentextend the existingIgxInputGroupComponent. For such a configuration to work, defining anIgxInputis required. In addition, all other components and directives available to theIgxInputGroupComponentcan also be used. - In order to enable date editing for both inputs, you need to decorate them with
igxDateTimeEditordirective.
Popup modes
By default, when clicked, the IgxDateRangePickerComponent opens its calendar pop-up in dropdown mode. Alternatively, the calendar can be opened in dialog mode by setting the Mode property to dialog.
<igx-date-range-picker [mode]="'dialog'"></igx-date-range-picker>
In a default configuration with a single read-only input, the calendar can be opened by clicking anywhere in the input, including the calendar icon. When there are two separate inputs for start and end date, and in dropdown mode, the calendar can only be opened from the calendar icon, since both inputs are editable by default. For two inputs in dialog mode, clicking anywhere in the input opens the calendar
The range value is set when dates are picked from the calendar. You will notice that in dropdown mode, the Done button is not available. In dialog mode, a Cancel button allows to revert the selection on close.
Keyboard Navigation
CuentaIgxDateRangePickerComponent con una navegación intuitiva por teclado, permitiendo a los usuarios incrementar, decrementar o saltar fácilmente entre diferentes componentes, todo ello sin necesidad de usar ratón.
Las opciones de navegación del teclado disponibles varían en función de si el componente está en modo de entrada única o de dos entradas.
Modo de dos entradas:
| Llaves | Descripción |
|---|---|
| ← | Mueve el símbolo de intercalación un carácter a la izquierda |
| → | Mueve el símbolo de intercalación un carácter a la derecha |
| Ctrl + ArrowLeft | Mueve el símbolo de intercalación al principio de la sección de máscara de entrada actual o al principio de la anterior si ya está al principio |
| Ctrl + ArrowRight | Mueve el símbolo de intercalación al final de la sección de máscara de entrada actual o al final de la siguiente si ya está al final |
| ArrowUp | Incrementa la parte actualmente "enfocada" de la máscara de entrada en un paso |
| ArrowDown | Disminuye la parte actualmente "enfocada" de la máscara de entrada en un paso |
| Hogar | Mueve el símbolo de intercalación al principio de la máscara de entrada |
| Fin | Mueve el símbolo de intercalación al final de la máscara de entrada |
| Ctrl + ; | Establece la fecha actual como el valor del componente |
Modos de entrada simple y doble:
| Llaves | Descripción |
|---|---|
| Alt + ArrowDown | Opens the calendar dropdown |
| Alt + ArrowUp | Closes the calendar dropdown |
La sección de navegación del teclado del calendario contiene todas las combinaciones de teclado que se pueden usar en el calendario.
Layout
Projecting components
To enrich the default Date Range Picker UX, the component allows projecting child components - the same as in the IgxInputGroupComponent: igxLabel, igx-hint / igxHint, igx-prefix / igxPrefix, igx-suffix / igxSuffix, excluding IgxInput. More detailed information about this can be found in the Label & Input topic.
<igx-date-range-picker #dateRangePicker [(ngModel)]="range">
<label igxLabel>Flight dates</label>
<igx-hint *ngIf="dateRangePicker.invalid">
Please choose start and end date!
</igx-hint>
</igx-date-range-picker>
O para dos entradas:
<igx-date-range-picker #dateRangePicker [(ngModel)]="range">
<igx-date-range-start>
...
<label igxLabel>Start Date</label>
<igx-hint *ngIf="dateRangePicker.invalid">
Please choose start and end date!
</igx-hint>
...
</igx-date-range-start>
<igx-date-range-end>
...
<label igxLabel>End Date</label>
...
</igx-date-range-end>
</igx-date-range-picker>
Alternar y borrar iconos
In the default configuration, with a single read-only input, a default calendar icon is shown as a prefix and a clear icon - as a suffix. These icons can be changed or redefined using the IgxPickerToggleComponent and IgxPickerClearComponent. They can be decorated with either igxPrefix or igxSuffix, which will define their position - at the start of the input or at the end respectively:
<igx-date-range-picker>
<igx-picker-toggle igxSuffix>
<igx-icon>calendar_view_day</igx-icon>
</igx-picker-toggle>
<igx-picker-clear igxSuffix>
<igx-icon>clear</igx-icon>
</igx-picker-clear>
</igx-date-range-picker>
When a Date Range Picker has two separate inputs for start and end dates, it doesn't expose these icons by default. The IgxPickerToggleComponent and IgxPickerClearComponent should be manually added as children of the IgxDateRangeStartComponent or IgxDateRangeEndComponent like so:
<igx-date-range-picker>
<igx-date-range-start>
...
<igx-picker-toggle igxPrefix>
<igx-icon>calendar_view_day</igx-icon>
</igx-picker-toggle>
<igx-picker-clear igxSuffix>
<igx-icon>clear</igx-icon>
</igx-picker-clear>
...
</igx-date-range-start>
<igx-date-range-end>
...
</igx-date-range-end>
</igx-date-range-picker>
Custom And Predefined Date Ranges
También puedes añadir chips de rango de fechas personalizados a la ventana emergente del calendario para una selección de rango más rápida usando lacustomRanges propiedad. Por ejemplo, puedes crear un chip personalizado para el rango de fechas que seleccione rápidamente el rango de los próximos 7 días, terminando con la fecha actual. Además, al establecer lausePredefinedRanges propiedad, se mostrará un conjunto de chips de rangos predefinidos junto con los personalizados.
public today = new Date();
public nextSeven = new Date(
this.today.getFullYear(),
this.today.getMonth(),
this.today.getDate() + 7
);
public customRanges: CustomDateRange[] = [
{
label: 'Next 7 days',
dateRange: {
start: this.today,
end: this.nextSeven
}
}
];
<igx-date-range-picker [usePredefinedRanges]="true" [customRanges]="customRanges"></igx-date-range-picker>
In addition, custom content or actions can be templated using the igxPickerActions directive. The following demo shows the predefined and custom ranges along with the templated actions:
Formatting
El componente Selector de rango de fechas admite diferentes formatos de visualización y entrada.
The display format of the value can be one of the listed Angular DatePipe formats. This allows it to support predefined format options, such as shortDate and longDate.
The inputFormat property accepts a constructed format string using characters supported by the DatePipe, e.g. MM/dd/yyyy, but doesn't support predefined format options, such as shortDate and longDate. If the inputFormat property is not defined then the Angular locale ID token is used when building it.
<igx-date-range-picker [(ngModel)]="range" required
inputFormat="dd/MM/yyyy" displayFormat="shortDate">
</igx-date-range-picker>
If the inputFormat property is not set, the input format will be inferred from the displayFormat in case it can be parsed as containing numeric date-time parts only.
Note
AhoraIgxDateRangePicker soporta entrada IME. Cuando termina la composición, el control convierte los números de carácter ancho en caracteres ASCII.
Forms and Validation
The Date Range Picker Component supports all directives from the core FormsModule, NgModel and ReactiveFormsModule (FormControl, FormGroup, etc.). This also includes the Forms Validators functions. In addition, the component's min and max values and disabledDates also act as form validators.
The NgModel and validators can be set on the IgxDateRangePickerComponent or on the individual start and end date inputs.
The following snippets and examples illustrate the use of the required validator in a Template-driven form.
Primero, necesitamos configurar el modelo para un único componente de rango de solo lectura, lo cual se realiza a nivel de componente:
<igx-date-range-picker [(ngModel)]="range" required>
<label igxLabel>Period</label>
</igx-date-range-picker>
Se puede utilizar la misma configuración al configurar dos entradas separadas. Tenga en cuenta que en este caso, la validación también se aplica a ambas entradas.
<igx-date-range-picker [(ngModel)]="range" required>
<igx-date-range-start>
<label igxLabel>Start Date</label>
<input igxInput igxDateTimeEditor type="text">
<igx-picker-toggle igxPrefix>
<igx-icon>calendar_today</igx-icon>
</igx-picker-toggle>
</igx-date-range-start>
<igx-date-range-end>
<label igxLabel>End Date</label>
<input igxInput igxDateTimeEditor type="text">
</igx-date-range-end>
</igx-date-range-picker>
Cuando se utilizan dos entradas separadas, es posible configurar el modelo y las propiedades requeridas en cada entrada. Tenga en cuenta que la validación es específica para cada entrada individual.
<igx-date-range-picker>
<igx-date-range-start>
<input igxInput igxDateTimeEditor [(ngModel)]="range.start" type="text" required>
</igx-date-range-start>
<igx-date-range-end>
<input igxInput igxDateTimeEditor [(ngModel)]="range.end" type="text" required>
</igx-date-range-end>
</igx-date-range-picker>
Min and max values
You can specify minValue and maxValue properties to restrict the user input by disabling calendar dates that are outside the range defined by those values.
public minDate = new Date(2020, 1, 15);
public maxDate = new Date(2020, 11, 1);
<igx-date-range-picker [(ngModel)]="range" required
[minValue]="minDate" [maxValue]="maxDate">
</igx-date-range-picker>
<igx-date-range-picker [minValue]="minDate" [maxValue]="maxDate">
<igx-date-range-start>
<input igxInput igxDateTimeEditor [(ngModel)]="range.start" type="text" required>
</igx-date-range-start>
<igx-date-range-end>
<input igxInput igxDateTimeEditor [(ngModel)]="range.end" type="text" required>
</igx-date-range-end>
</igx-date-range-picker>
The IgxDateRangePickerComponent is also a validator which means it controls its validity internally using minValue and maxValue. You can also access both of them through ngModel:
<igx-date-range-picker #dateRangePicker="ngModel" [(ngModel)]="range" required
[minValue]="minDate" [maxValue]="maxDate">
<igx-date-range-start>
<input igxInput igxDateTimeEditor type="text">
</igx-date-range-start>
<igx-date-range-end>
<input igxInput igxDateTimeEditor type="text">
</igx-date-range-end>
</igx-date-range-picker>
<!-- minValue & maxValue will be true if the current range does not satisfy them -->
<div *ngIf="dateRangePicker.minValue || dateRangePicker.maxValue">
<p>Value not in range.</p>
</div>
Disabled And Special dates
También tienes la opción de establecer fechas desactivadas en el calendario para reducir el rango de fechas que el usuario puede elegir. Para establecer las fechas de desactivación, puedes usar ladisabledDates propiedad.
export class DateRangeSampleComponent implements OnInit {
@ViewChild('dateRange') public dateRange: IgxDateRangePicker;
public minDate = new Date(2025, 4, 1);
public maxDate = new Date(2025, 4, 31);
public ngOnInit() {
this.dateRange.disabledDates = [
{
type: DateRangeType.Between,
dateRange: [minDate, maxDate]
}
] as DateRangeDescriptor[];
}
}
You can see more information about all the possibilities that the DisabledDates property offers here: calendar disabled dates.
You can also do the same if you want to set one or more special dates in the calendar; the only difference is that you need to use the SpecialDates property instead. Special dates
Templating
When two editors are used, the default separator can be replaced using the igxDateRangeSeparator directive. Here is how to change the date separator to a hyphen -:
<igx-date-range-picker>
<igx-date-range-start>
<input igxInput igxDateTimeEditor [(ngModel)]="range.start" type="text" required>
</igx-date-range-start>
<ng-template igxDateRangeSeparator>-</ng-template>
<igx-date-range-end>
<input igxInput igxDateTimeEditor [(ngModel)]="range.end" type="text" required>
</igx-date-range-end>
</igx-date-range-picker>
Calendar specific settings
Puede personalizar aún más el calendario emergente utilizando varias propiedades. Puede encontrar más información sobre cómo afectan al calendario en el tema IgxCalendarComponent.
| Nombre | Tipo | Descripción |
|---|---|---|
orientation |
'vertical' or 'horizontal' | Permite establecer si el calendario debe visualizarse vertical u horizontalmente. |
displayMonthsCount |
cadena | Controla cuántos meses son visibles a la vez, con un valor de 1 o 2. |
showWeekNumbers |
cadena | Habilita o deshabilita la columna de número de semana en el calendario. |
weekStart |
cadena | Establece el día de inicio de la semana. |
hideOutsideDays |
booleano | Oculta los días que quedan fuera de la vista del mes actual. |
hideHeader |
booleano | Oculta el encabezado del calendario (aplicable solo en el modo de diálogo). |
headerOrientation |
'vertical' or 'horizontal' | Aligns the calendar header vertically or horizontally (dialog mode only). |
activeDate |
Fecha | Establece la fecha que se resalta inicialmente en el calendario. Si no se establece, la fecha actual se convierte en la fecha activa. |
<igx-date-range-picker [hideHeader]="true"
[orientation]="'vertical'"
[headerOrientation]="'horizontal'"
[displayMonthsCount]="1">
</igx-date-range-picker>
The header, subheader and title parts of the calendar header can be customized by leveraging the igxCalendarHeader, igxCalendarSubheader and the igxCalendarHeaderTitle template directives, for example:
<igx-date-range-picker [value]="date">
<ng-template igxCalendarHeader let-format>
{{ format.month.combined | titlecase }}{{format.day.combined }}{{ format.weekday.combined }}
</ng-template>
<ng-template igxCalendarSubheader let-format>
<span (click)="format.yearView()">{{ format.year.combined }}</span>
<span (click)="format.monthView()">{{ format.month.combined | titlecase }}</span>
</ng-template>
<ng-template igxCalendarHeaderTitle let-format>
<span>My calendar</span>
</ng-template>
</igx-date--range-picker>
Estilismo
To get started with styling the igxDateRangePicker, we need to import the index file, where all the theme functions and component mixins live:
@use "igniteui-angular/theming" as *;
// IMPORTANT: Prior to Ignite UI for Angular version 13 use:
// @import '~igniteui-angular/lib/core/styles/themes/index';
The Date Range Picker Component exposes date-range-picker-theme and utilizes several components and directives, including igxInputGroupComponent, igxCalendar and igxOverlay. Any global styling for the aforementioned components and directives will affect the igxDateRangeComponent. As the Date Range Picker Component uses the input group and calendar themes, we have to create new themes that extend the calendar-theme and input-group-theme and use some of their parameters to style the date range picker in conjunction with the date range picker theme. We will use a single custom color palette to define the colors to use across all themes:
// COMMON
$purple: #9E379F;
$blue: #61AEDB;
$light-gray: #efefef;
$custom-palette: palette(
$primary: $blue,
$secondary: $purple,
$surface: $light-gray
);
$today-text: color($custom-palette, "primary", 500);
$text-color: color($custom-palette, "secondary", 200);
$color-focused: color($custom-palette, "secondary", 500);
// DATE-RANGE
$custom-date-range-theme: date-range-picker-theme(
$label-color: $color-focused
);
// INPUT GROUP
$custom-input-group-theme: input-group-theme(
$filled-text-color: $text-color,
$idle-text-color: $text-color,
$focused-text-color: $color-focused,
$idle-bottom-line-color: $purple,
$hover-bottom-line-color: $color-focused,
$interim-bottom-line-color: $color-focused
);
// CALENDAR
$custom-calendar-theme: calendar-theme(
$date-current-foreground: $today-text,
$border-radius: 0.5,
$date-border-radius: 0.5
);
El último paso es pasar los temas personalizados:
@include css-vars($custom-date-range-theme);
@include css-vars($custom-input-group-theme);
@include css-vars($custom-calendar-theme);
Warning
Si el componente utiliza unaEmulated ViewEncapsulation, es necesario quepenetrate esta encapsulación utilice::ng-deep
:host {
::ng-deep {
@include date-range-picker($custom-date-range-theme);
@include input-group($custom-input-group-theme);
@include calendar($custom-calendar-theme);
}
}
Scoping Styles
Con respecto al alcance del estilo, debe consultar las secciones de estilo [Estilos de componentes con alcance de superposición] (overlay-styling.md#Estilos de superposición con alcance) y Estilos de alcance del grupo de entrada, ya que brindan más información.
Application Demo
The demo below defines a form for flight tickets that uses the IgxDateRangePickerComponent. If no dates are selected, an IgxHint is used to display a validation error. The selection of the dates is restricted by the minValue and maxValue properties of the IgxDateRangePickerComponent
API References
- Componente IgxDateRangePicker
- Componente IgxCalendar
- Estilos de componentes IgxCalendar
- Estilos de superposición Igx
- Componente IgxInputGroup
Theming Dependencies
- Tema IgxCalendario
- Tema IgxOverlay
- Tema IgxIcon
- Tema IgxButton
- Tema IgxInputGroup
- Tema desplegable Igx
Additional Resources
Temas relacionados:
Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.