Angular 날짜 범위 선택기 구성 요소 개요

    Angular 날짜 범위 선택기는 텍스트 입력과 달력 팝업을 포함하는 경량 구성 요소로, 사용자가 시작 날짜와 종료 날짜를 쉽게 선택할 수 있습니다. 다양한 애플리케이션 요구 사항에 맞게 사용자 정의가 가능하며 날짜 범위 제한, 구성 가능한 날짜 형식 등과 같은 기능을 제공합니다.

    Angular Date Range Picker Example

    아래는 사용자가 시작일과 종료일을 선택할 수 있도록 캘린더 팝업을 통해 구성 요소를 시연IgxDateRangePickerComponent 한 샘플입니다.

    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
    

    Ignite UI for Angular에 대한 전체 소개는 시작 항목을 참조하십시오.

    다음 단계는 다음 단계를 가져오는 것입니다.IgxDateRangePickerModule 당신의 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

    기본 모드에서 날짜 범위 선택기를 인스턴스화하려면 다음 코드를 사용하세요.

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

    선택기는 날짜 값을 표시하기 위한 두 가지 모드(단일 입력 및 두 입력)를 제공합니다. 단일 입력 모드에서는 필드를 편집할 수 없으며 입력하여 날짜 범위를 편집할 수 없습니다. 그러나 두 가지 입력 모드에서는 사용자가 별도의 입력 필드에 입력하여 시작 날짜와 종료 날짜를 편집할 수 있습니다.

    달력이 표시되면 시작 날짜와 종료 날짜를 모두 선택하여 날짜 범위를 선택할 수 있습니다. 날짜를 선택하면 시작 날짜와 종료 날짜가 모두 설정되고 두 번째 날짜를 선택하면 종료 날짜가 설정됩니다. 범위가 이미 선택되어 있는 경우 달력에서 다른 날짜를 클릭하면 새 범위 선택이 시작됩니다.

    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>
    

    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

    IgxDateRangePickerComponent직관적인 키보드 내비게이션 기능을 제공하여, 사용자가 마우스 없이도 다양한 구성 요소 사이를 쉽게 늘리거나 감소하거나 점프할 수 있습니다.

    사용 가능한 키보드 탐색 옵션은 구성 요소가 단일 입력 모드인지 두 입력 모드인지에 따라 달라집니다.

    두 개의 입력 모드:

    열쇠 설명
    캐럿을 왼쪽으로 한 문자 이동합니다.
    캐럿을 오른쪽으로 한 문자 이동합니다.
    Ctrl + ArrowLeft 캐럿을 현재 입력 마스크 섹션의 시작 부분으로 이동하거나 이미 시작 부분에 있는 경우 이전 섹션의 시작 부분으로 이동합니다
    Ctrl + ArrowRight 캐럿을 현재 입력 마스크 섹션의 끝으로 이동하거나 이미 끝에 있는 경우 다음 섹션의 끝으로 이동합니다.
    ArrowUp 입력 마스크의 현재 "초점이 맞춰진" 부분을 한 단계씩 증가시킵니다
    ArrowDown 입력 마스크의 현재 "초점이 맞춰진" 부분을 한 단계 감소시킵니다.
    캐럿을 입력 마스크의 시작 부분으로 이동합니다.
    캐럿을 입력 마스크의 끝으로 이동합니다.
    Ctrl + ; 현재 날짜를 구성 요소의 값으로 설정합니다.

    단일 및 두 개의 입력 모드 모두:

    열쇠 설명
    Alt + ArrowDown Opens the calendar dropdown
    Alt + ArrowUp Closes the calendar dropdown

    달력 키보드 탐색 섹션에는 달력에서 사용할 수 있는 모든 키보드 조합이 포함되어 있습니다.

    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>
    

    또는 두 개의 입력에 대해:

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

    아이콘 전환 및 지우기

    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

    또한 캘린더 팝업에 맞춤형 날짜 범위 칩을 추가해 더 빠른 범위 선택customRanges을 할 수도 있습니다. 예를 들어, 다가오는 7일간의 범위를 빠르게 선택할 수 있는 맞춤형 날짜 범위 칩을 만들 수 있으며, 그 범위는 현재 날짜로 끝납니다. 또한, 속성을 설정usePredefinedRanges 하면 미리 정의된 범위 칩 세트가 커스텀 칩과 함께 표시됩니다.

    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

    날짜 범위 선택기 구성요소는 다양한 표시 및 입력 형식을 지원합니다.

    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

    이제는IgxDateRangePicker IME 입력을 지원합니다. 컴포지션이 끝나면 컨트롤은 넓은 문자 숫자를 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.

    먼저 단일 읽기 전용 범위 구성 요소에 대한 모델을 설정해야 하며 이는 구성 요소 수준에서 수행됩니다.

    <igx-date-range-picker [(ngModel)]="range" required>
        <label igxLabel>Period</label>
    </igx-date-range-picker>
    

    두 개의 개별 입력을 설정할 때 동일한 구성을 사용할 수 있습니다. 이 경우 유효성 검사는 두 입력 모두에도 적용됩니다.

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

    두 개의 별도 입력을 사용하는 경우 각 입력에 모델 및 필수 속성을 설정할 수 있습니다. 유효성 검사는 각 개별 입력에 따라 다릅니다.

    <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

    또한 사용자가 선택할 수 있는 날짜 범위를 좁히기 위해 달력에서 비활성화된 날짜를 설정할 수 있습니다. 비활성화 날짜를 설정하려면 해당disabledDates 속성을 사용할 수 있습니다.

    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

    다양한 속성을 사용하여 팝업 달력을 추가로 사용자 지정할 수 있습니다. 이러한 기능이 달력에 미치는 영향에 대한 자세한 내용은 IgxCalendarComponent 항목에서 찾을 수 있습니다.

    이름 유형 설명
    orientation 'vertical' or 'horizontal' 달력을 세로로 표시할지 가로로 표시할지 여부를 설정할 수 있습니다.
    displayMonthsCount 한 번에 표시되는 개월 수를 1 또는 2 값으로 제어합니다.
    showWeekNumbers 달력에서 주 번호 열을 활성화하거나 비활성화합니다.
    weekStart 주의 시작 요일을 설정합니다.
    hideOutsideDays 부울 현재 월 보기를 벗어나는 날짜를 숨깁니다.
    hideHeader 부울 달력 헤더를 숨깁니다(대화 상자 모드에서만 적용 가능).
    headerOrientation 'vertical' or 'horizontal' Aligns the calendar header vertically or horizontally (dialog mode only).
    activeDate 날짜 달력에서 처음에 강조 표시된 날짜를 설정합니다. 설정하지 않으면 현재 날짜가 활성 날짜가 됩니다.
     <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>
    

    스타일링

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

    마지막 단계는 사용자 정의 테마를 전달하는 것입니다.

    @include css-vars($custom-date-range-theme);
    @include css-vars($custom-input-group-theme);
    @include css-vars($custom-calendar-theme);
    
    Warning

    만약 컴포넌트가 ViewEncapsulation을 사용Emulated 한다면, 이 캡슐화는penetrate 다음을 통해 필요합니다.::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

    스타일 범위 지정과 관련하여 자세한 정보를 제공하는 스타일 섹션 [오버레이 범위 지정 구성요소 스타일](overlay-styling.md#Scoped 오버레이 스타일) 및 입력 그룹 범위 지정 스타일을 모두 참조해야 합니다.

    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

    Theming Dependencies

    Additional Resources

    관련 주제:

    우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.