Descripción general del componente del selector de fecha de Angular

    Angular selector de fecha es un componente rico en funciones que se utiliza para introducir una fecha mediante la entrada manual de texto o elegir valores de fecha en un cuadro de diálogo de calendario que aparece. Ligero y fácil de usar, el selector de fecha en Angular permite a los usuarios navegar a una fecha deseada con varias opciones de visualización: mes, año, década. Existen las propiedades mínimas, máximas y obligatorias habituales para agregar validación.

    El componente Selector de fecha Ignite UI for Angular permite a los usuarios elegir una sola fecha a través de un menú desplegable de calendario de vista mensual o un campo de entrada editable. El selector de fecha de Angular también admite un modo de cuadro de diálogo para la selección solo del calendario, el formato de fecha personalizable y la configuración regional y la integración de validación.

    Angular Date Picker Example

    A continuación, puede ver un ejemplo que demuestra cómo funciona el selector de fecha Angular cuando los usuarios pueden elegir una fecha a través de una entrada de texto manual y hacer clic en el icono del calendario a la izquierda para navegar hasta él. Vea cómo renderizarlo.

    Getting Started with Ignite UI for Angular Date Picker

    Para empezar a utilizar el componente Selector de fecha Ignite UI for Angular, primero debe instalar Ignite UI for Angular. En una aplicación Angular existente, escriba el siguiente comando:

    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 importarlosIgxDatePickerModule en tu archivo app.module.ts.

    Note

    Como el selector usa IgxCalendarComponent, también depende de BrowserAnimationsModule y, opcionalmente, de HammerModule para las interacciones táctiles, por lo que también deben agregarse al 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 puedes importarlosIgxDatePickerComponent como una dependencia independiente, o usar elIGX_DATE_PICKER_DIRECTIVES token para importar el componente y todos sus componentes y directivas de soporte.

    // 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>
    

    Puede encontrar más información sobre esto en la sección ISO del 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>
    

    El fragmento anterior agregará un icono de alternancia adicional al final de la entrada, justo después del icono de borrado predeterminado. Sin embargo, esto no eliminará el icono de alternancia predeterminado, ya que los prefijos y sufijos se pueden apilar uno tras otro.

    Personalización de los iconos de alternar y borrar

    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>
    

    Botones de acción personalizados

    Los botones de acción del selector se pueden modificar de dos maneras:

    <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:

    Llaves Descripción
    Espacio Muestra la ventana emergente del calendario y la enfoca.
    Alt + Muestra la ventana emergente del calendario y la enfoca.
    Esc Cierra la ventana emergente del calendario y enfoca el campo de entrada.
    Ingresar Cierra la ventana emergente del calendario, selecciona la fecha enfocada y mueve el foco al campo de entrada
    Alt + Cierra la ventana emergente del calendario y enfoca el campo de entrada.

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

    Examples

    Dialog Mode

    The IgxDatePickerComponent also supports a dialog mode:

    <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

    The IgxDatePicker now supports IME input. When composition ends, the control converts the wide-character numbers to ASCII characters.

    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 el selector de fecha y 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.

    To achieve that in template driven forms, use the ngModel to bind both components to the same Date object.

    In reactive forms, we can handle the valueChange event of each component and update the value of the other.

    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.

    Así es como se vería un selector de fecha Angular con una definición de configuración regional 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>
    

    Estilismo

    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,
    );
    

    El último paso es pasar el tema personalizado del selector de fechas:

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

    If the component is using an Emulated ViewEncapsulation, it is necessary to penetrate this encapsulation using ::ng-deep

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

    API References

    Theming Dependencies

    Additional Resources

    Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.