Visão geral do componente Angular Date Picker

    Angular Date Picker é um componente rico em recursos usado para inserir uma data por meio de entrada manual de texto ou escolher valores de data em uma caixa de diálogo de calendário que aparece. Leve e simples de usar, o Date Picker no Angular permite que os usuários naveguem até uma data desejada com várias opções de visualização – mês, ano, década. Existem as propriedades usuais min, max e required para adicionar validação.

    O Ignite UI for Angular Date Picker Component permite que os usuários escolham uma única data por meio de um menu suspenso de calendário de visualização mensal ou campo de entrada editável. O Angular Date Picker também oferece suporte a um modo de diálogo para seleção somente do calendário, formatação de data personalizável e com reconhecimento de localidade e integração de validação.

    Angular Date Picker Example

    Abaixo você pode ver um exemplo que demonstra como o Angular Date Picker funciona quando os usuários estão habilitados a escolher uma data por meio de uma entrada de texto manual e clicar no ícone de calendário à esquerda para navegar até ela. Veja como renderizá-lo.

    Getting Started with Ignite UI for Angular Date Picker

    Para começar a usar o componente Ignite UI for Angular Date Picker, primeiro você precisa instalar Ignite UI for Angular. Em um aplicativo Angular existente, digite o seguinte comando:

    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 issoIgxDatePickerModule no seu arquivo app.module.ts.

    Note

    Como o seletor usa o IgxCalendarComponent, ele também depende do BrowserAnimationsModule e, opcionalmente, do HammerModule para interações de toque, então eles também precisam ser adicionados ao módulo:

    import { HammerModule } from '@angular/platform-browser';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { IgxDatePickerModule } from 'igniteui-angular';
    // import { IgxDatePickerModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        ...
        imports: [..., IgxDatePickerModule, BrowserAnimationsModule, HammerModule],
        ...
    })
    export class AppModule {}
    

    Alternativamente,16.0.0 você pode importarIgxDatePickerComponent como uma dependência independente ou usar oIGX_DATE_PICKER_DIRECTIVES token para importar o componente e todos os seus componentes e diretivas de suporte.

    // home.component.ts
    
    import { HammerModule } from '@angular/platform-browser';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { IGX_DATE_PICKER_DIRECTIVES } from 'igniteui-angular';
    // import { IGX_DATE_PICKER_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-date-picker>
            <label igxLabel>Date</label>
        </igx-date-picker>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [BrowserAnimationsModule, HammerModule, IGX_DATE_PICKER_DIRECTIVES]
        /* or imports: [BrowserAnimationsModule, HammerModule, IgxDatePickerComponent, IgxLabelDirective] */
    })
    export class HomeComponent {}
    

    Now that you have the Ignite UI for Angular Date Picker module or directives imported, you can start using the igx-date-picker component.

    Using the Angular Date Picker Component

    Display Date picker

    To instantiate a Date Picker in its default dropdown state, use the following code:

    <igx-date-picker>
        <label igxLabel>Date</label>
    </igx-date-picker>
    

    Options

    The IgxDatePickerComponent can be bound to a date or a string.

    <igx-date-picker [value]="date"></igx-date-picker>
    
    public date = new Date(2000, 0, 1);
    

    If a string is bound to the picker, it needs to be a date-only string in the ISO 8601 format:

    <igx-date-picker [value]="'2000-01-01'"></igx-date-picker>
    

    Mais informações sobre isso podem ser encontradas na seção ISO do Editor DateTime.

    Two-way binding is possible through ngModel:

    <igx-date-picker [(ngModel)]="date"></igx-date-picker>
    

    As well as through the value input:

    <igx-date-picker [(value)]="date"></igx-date-picker>
    

    Additionally, formControlName can be set on the picker, to use it in a reactive form:

    <form [formGroup]="form">
        <igx-date-picker formControlName="datePicker"></igx-date-picker>
    </form>
    
    export class SampleFormComponent {
        // ...
        public form: FormGroup;
        constructor(private fb: FormBuilder) {
            this.form = this.fb.group({
                datePicker: ['', Validators.required]
            });
        }
    }
    
    Note

    The picker always returns a Date value, this means that If it is model bound or two-way bound to a string variable, after a new date has been chosen, it will be of type Date.

    Projecting components

    The IgxDatePickerComponent allows the projection of child components that the IgxInputGroupComponent supports (with the exception of IgxInput) - igxLabel, igx-hint / IgxHint, igx-prefix / igxPrefix, igx-suffix / igxSuffix. More detailed information about this can be found in the Label & Input topic.

    <igx-date-picker #datePicker>
        <igx-icon igxSuffix (click)="datePicker.open()">keyboard_arrow_down</igx-icon>
    </igx-date-picker>
    

    O snippet acima adicionará um ícone de alternância adicional no final da entrada, logo após o ícone de limpeza padrão. Isso não removerá o ícone de alternância padrão, embora prefixos e sufixos possam ser empilhados um após o outro.

    Personalizando os ícones de alternância e limpeza

    The IgxDatePickerComponent can be configured with IgxPickerToggleComponent and IgxPickerClearComponent. These can be used to change the toggle and clear icons without having to add your own click handlers.

     <igx-date-picker>
        <label igxLabel>Select a Date</label>
        <igx-picker-toggle igxPrefix>
            <igx-icon>calendar_view_day</igx-icon>
        </igx-picker-toggle>
        <igx-picker-clear igxSuffix>
            <igx-icon>delete</igx-icon>
        </igx-picker-clear>
    </igx-date-picker>
    

    Botões de ação personalizados

    Os botões de ação do seletor podem ser modificados de duas maneiras:

    <igx-date-picker [todayButtonLabel]="'今日'" [cancelButtonLabel]="'キャンセル'"></igx-date-picker>
    
    • the whole buttons can be templated using the igxPickerActions directive: With it you gain access to the date picker's calendar and all of its members:
    <igx-date-picker>
        <ng-template igxPickerActions let-calendar>
            <button igxButton="flat" (click)="calendar.viewDate = today">Today</button>
        </ng-template>
    </igx-date-picker>
    

    Keyboard Navigation

    Opening and closing the IgxDatePickerComponent's calendar UI with the keyboard is available only for dropdown mode and can be triggered via the key combinations below:

    Chaves Descrição
    Espaço Exibe o pop-up do calendário e o focaliza
    Alt + Exibe o pop-up do calendário e o focaliza
    Esc Fecha o pop-up do calendário e foca o campo de entrada
    Entrar Fecha o pop-up do calendário, seleciona a data em foco e move o foco para o campo de entrada
    Alt + Fecha o pop-up do calendário e foca o campo de entrada

    Since the IgxDatePickerComponent uses the IgxDateTimeEditorDirective it inherits its keyboard navigation.

    Examples

    Dialog Mode

    TambémIgxDatePickerComponent suporta umdialog modo:

    <igx-date-picker [mode]="'dialog'"></igx-date-picker>
    

    Display and input format

    inputFormat and displayFormat are properties which can be set to make the picker's editor follow a specified format. The inputFormat property is used when the picker is in dropdown mode and it governs the input's editable mask, as well as its placeholder (if none is set). Additionally, the inputFormat is locale based, so if none is provided, the picker will default to the one used by the browser.

    A good thing to note is that the the Angular Date Picker Component in Ignite UI will always add a leading zero on the date and month portions if they were provided in a format that does not have it, e.g. d/M/yy becomes dd/MM/yy. This applies only during editing.

    displayFormat on the other hand uses Angular's DatePipe and is used to format the picker's input when it is not focused. If no displayFormat is provided, the picker will use the inputFormat as its displayFormat. Alternatively, 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.

    More information about these can be found in the IgxDateTimeEditor examples section.

    Note

    OIgxDatePicker agora suporta entrada de IME. Quando a composição termina, o controle converte os números de caracteres largos para caracteres ASCII.

    Increment and decrement

    The IgxDatePickerComponent exposes increment and decrement methods. Both of which come from the IgxDateTimeEditorDirective and can be used for incrementing and decrementing a specific DatePart of the currently set date.

    <igx-date-picker #datePicker>
        <igx-icon igxPrefix (click)="datePicker.increment(DatePart.Month, 3)">keyboard_arrow_up</igx-icon>
        <igx-icon igxPrefix (click)="datePicker.decrement(DatePart.Year. 4)">keyboard_arrow_down</igx-icon>
    </igx-date-picker>
    

    It also has as a spinDelta input property which can be used to increment or decrement a specific date part of the currently set date.

    <igx-date-picker [spinDelta]="{date: 2, month: 3, year: 4}"></igx-date-picker>
    

    In Angular Forms

    The IgxDatePickerComponent 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 minValue and maxValue properties act as form validators.

    You can see the IgxDatePickerComponent in a reactive form by visiting our Reactive Forms Integration topic.

    Usando o seletor de data e hora juntos

    In some cases when the IgxDatePicker and the IgxTimePicker are used together, we might need them to be bound to one and the same Date object value.

    Para alcançar isso em formulários baseados em templates, use ongModel para vincular ambos os componentes ao mesmo objeto Data.

    Em formas reativas, podemos lidar com ovalueChange evento de cada componente e atualizar o valor do outro.

    Calendar Specific settings

    The IgxDatePickerComponent uses the IgxCalendarComponent and you can modify some of its settings via the properties that the date picker exposes. Some of these include displayMonthsCount which allows more than one calendar to be displayed when the picker expands, weekStart which determines the starting day of the week, showWeekNumbers which shows the number for each week in the year and more.

    Internationalization

    The localization of the IgxDatePickerComponent can be controlled through its locale input. Additionally, using the igxCalendarHeader and the igxCalendarSubheader templates, provided by the IgxCalendarComponent, you can specify the look of your header and subheader. More information on how to use these templates can be found in the IgxCalendarComponent topic.

    Veja como ficaria um Angular Date Picker com definição de localidade japonesa:

    <igx-date-picker locale="ja-JP" [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>
    </igx-date-picker>
    

    Estilização

    To get started with styling the date picker, 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 Angular Date Picker uses the calendar's theme, so we have to create a new theme that extends the calendar-theme. By setting the $header-background, the theme automatically computes the necessary colors for the other properties to ensure a visually balanced and accessible design.

    $custom-datepicker-theme: calendar-theme(
      $header-background: #57a5cd,
    );
    

    O último passo é passar o tema personalizado do Date Picker:

    @include css-vars($custom-datepicker-theme);
    
    Warning

    Se o componente estiver usando umEmulated ViewEncapsulation, é necessário parapenetrate esse encapsulamento usando::ng-deep

    :host {
      ::ng-deep {
        @include css-vars($custom-datepicker-theme);
      }
    }
    

    API References

    Theming Dependencies

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.