Visão geral do componente Angular Date Range Picker
O Angular Seletor de Intervalo de Datas é um componente leve que inclui uma entrada de texto e um pop-up de calendário, permitindo que os usuários selecionem facilmente as datas de início e término. É altamente personalizável para atender a vários requisitos de aplicativos, oferecendo recursos como restrições de intervalo de datas, formatos de data configuráveis e muito mais.
Angular Date Range Picker Example
Below is a sample demonstrating the IgxDateRangePickerComponent component in action, where a calendar pop-up allows users to select start and end dates.
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 obter uma introdução completa ao Ignite UI for Angular, leia o tópico de introdução.
O próximo passo é importar issoIgxDateRangePickerModule no seu arquivo 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 instanciar um seletor de intervalo de datas em seu modo padrão, use o seguinte 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.
O seletor oferece dois modos para exibir valores de data: entrada única e duas entradas. No modo de entrada única, o campo não é editável e o intervalo de datas não pode ser editado digitando. No modo de duas entradas, no entanto, os usuários podem editar as datas de início e término digitando em campos de entrada separados.
Quando o calendário está visível, um intervalo de datas pode ser selecionado escolhendo uma data de início e término. A seleção de uma data definirá a data de início e término e, assim que uma segunda data for escolhida, definirá a data de término. Se um intervalo já estiver selecionado, clicar em qualquer outra data no calendário iniciará uma nova seleção 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
The IgxDateRangePickerComponent features intuitive keyboard navigation, allowing users to easily increment, decrement, or jump between different component parts, all without needing to use a mouse.
As opções de navegação do teclado disponíveis variam dependendo se o componente está no modo de entrada única ou de duas entradas.
Modo de duas entradas:
| Chaves | Descrição |
|---|---|
| ← | Move o cursor um caractere para a esquerda |
| → | Move o cursor um caractere para a direita |
| Ctrl + ArrowLeft | Move o cursor para o início da seção de máscara de entrada atual ou para o início da anterior, se já estiver no início |
| Ctrl + ArrowRight | Move o cursor para o final da seção de máscara de entrada atual ou para o final da próxima, se já estiver no final |
| ArrowUp | Incrementa a parte atualmente "focada" da máscara de entrada em uma etapa |
| ArrowDown | Diminui a parte atualmente "focada" da máscara de entrada em um passo |
| Casa | Move o cursor para o início da máscara de entrada |
| Fim | Move o cursor para o final da máscara de entrada |
| Ctrl + ; | Define a data atual como o valor do componente |
Modos de entrada única e dupla:
| Chaves | Descrição |
|---|---|
| Alt + ArrowDown | Opens the calendar dropdown |
| Alt + ArrowUp | Closes the calendar dropdown |
A seção de navegação do teclado do calendário contém todas as combinações de teclado que podem ser usadas no calendário.
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>
Ou para duas 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 e limpar ícones
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
You can also add custom date range chips to the calendar pop-up for faster range selection using the customRanges property. For example, you can create a custom date range chip to quickly select the range for the upcoming 7 days, ending with the current date. In addition, by setting the usePredefinedRanges property, a set of predefined ranges chips will be displayed along with the custom ones.
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
O componente Seletor de intervalo de datas oferece suporte a diferentes formatos de exibição e 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
OIgxDateRangePicker agora suporta entrada de IME. Quando a composição termina, o controle converte os números de caracteres largos para 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.
Primeiro, precisamos configurar o modelo para um único componente de intervalo somente leitura, o que é feito no nível do componente:
<igx-date-range-picker [(ngModel)]="range" required>
<label igxLabel>Period</label>
</igx-date-range-picker>
A mesma configuração pode ser usada ao definir duas entradas separadas. Note que, neste caso, a validação também é aplicada a ambas as 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>
Ao usar duas entradas separadas, é possível definir o modelo e as propriedades necessárias em cada entrada. Observe que a validação é 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
You also have the ability to set disabled dates in the calendar to narrow the range of dates the user can choose from. To set the disabled dates, you can use the disabledDates property.
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
Você pode personalizar ainda mais o calendário pop-up usando várias propriedades. Mais informações sobre como isso afeta o calendário podem ser encontradas no tópico IgxCalendarComponent.
| Nome | Tipo | Descrição |
|---|---|---|
orientation |
'vertical' or 'horizontal' | Permite definir se o calendário deve ser exibido vertical ou horizontalmente. |
displayMonthsCount |
corda | Controla quantos meses são visíveis por vez, com um valor de 1 ou 2. |
showWeekNumbers |
corda | Ativa ou desativa a coluna de número da semana no calendário. |
weekStart |
corda | Define o dia de início da semana. |
hideOutsideDays |
booleano | Oculta os dias que estão fora da exibição do mês atual. |
hideHeader |
booleano | Oculta o cabeçalho do calendário (aplicável somente no modo de diálogo). |
headerOrientation |
'vertical' or 'horizontal' | Aligns the calendar header vertically or horizontally (dialog mode only). |
activeDate |
Data | Define a data inicialmente destacada no calendário. Se não for definida, a data atual se tornará a data ativa. |
<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>
Estilização
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
);
O último passo é passar os temas personalizados:
@include css-vars($custom-date-range-theme);
@include css-vars($custom-input-group-theme);
@include css-vars($custom-calendar-theme);
Warning
If the component is using an Emulated ViewEncapsulation, it is necessary to penetrate this encapsulation using ::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
Em relação ao escopo de estilo, você deve consultar as seções de estilo [Estilos de componentes com escopo de sobreposição](overlay-styling.md#Estilos de sobreposição com escopo) e Estilos de escopo de grupo de entrada, pois elas fornecem mais informações.
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 IgxCalendarComponent
- Estilos IgxOverlay
- Componente do grupo de entrada Igx
Theming Dependencies
Additional Resources
Tópicos relacionados:
Nossa comunidade é ativa e sempre acolhedora para novas ideias.