Angular Time Picker 개요

    시간 선택기 구성요소를 사용하면 사용자는 드롭다운이나 스피너가 있는 대화상자에서 '날짜' 개체의 시간 부분을 입력하거나 선택할 수 있으며, 이는 입력 필드에 미러링됩니다. 기본 모드인 드롭다운 모드에서는 입력 필드를 편집할 수 있으며 사용자는 선택한 시간도 편집할 수 있습니다.

    시간 선택기 구성 요소에는 시계 버튼을 표시하기 위한 다양한 내장 템플릿과 유효성 검사, 사용자 정의 시간 형식 지정 등과 같은 기능이 있습니다.

    Angular Time Picker Example

    일반적으로 사용자는 텍스트 입력을 통해 또는 Angular Time Picker 드롭다운에서 시간 값을 선택하여 선호하는 시간을 입력할 수 있습니다. 아래의 기본 Angular Time Picker 예는 사용자가 드롭다운이나 키보드를 사용하여 값을 쉽게 입력하는 방법을 보여줍니다.

    Getting Started with Ignite UI for Angular Time Picker

    Ignite UI for Angular Time Picker 구성 요소를 시작하려면 먼저 Ignite UI for Angular 설치해야 합니다. 기존 Angular 애플리케이션에서 다음 명령을 입력합니다.

    ng add igniteui-angular
    

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

    다음 단계는 다음 단계를 가져오는 것입니다.IgxTimePickerModule 당신의 app.module.ts 파일.

    Note

    또한 IgxTimePicker는 터치 조작을 위해 BrowserAnimationsModule선택적으로​ ​HammerModule에 종속됩니다. AppModule에도 추가해야 합니다.

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

    또는16.0.0 독립 실행형 의존성으로 가져오IgxTimePickerComponent 거나, 토큰을IGX_TIME_PICKER_DIRECTIVES 사용해 컴포넌트와 그 지원 컴포넌트, 명령어를 가져올 수도 있습니다.

    // home.component.ts
    
    import { FormsModule } from '@angular/forms';
    import { IGX_TIME_PICKER_DIRECTIVES } from 'igniteui-angular';
    // import { IGX_TABS_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: '<igx-time-picker [(ngModel)]="time"></igx-time-picker>',
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IGX_TIME_PICKER_DIRECTIVES, FormsModule]
        /* or imports: [IgxTimePickerComponent, FormsModule] */
    })
    export class HomeComponent {
        public time: Date;
    }
    

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

    Using the Angular Time Picker

    Default

    템플릿에 시간 선택기를 추가하려면 다음 코드를 사용하세요.

    <!--meeting.component.html-->
    <igx-time-picker></igx-time-picker>
    

    출력은 데모의 출력과 동일해야 합니다.

    Binding

    The Time Picker in Angular can be bound to either a Date object or time-only string value in ISO 8601 format by setting the value property or ngModel.

    First create a time string in ISO 8601 format:

    public time = '09:15:30';
    

    Then use the ngModel to create a two-way data-binding:

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

    or set value input in the template:

    <igx-time-picker [value]="time"></igx-time-picker>
    

    To use it in a reactive form you need to set a formControlName on the picker

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

    Projecting components

    The time picker component allows projecting child components - the same as in the IgxInputGroupComponent: igxLabel, IgxHint, igxPrefix, igxSuffix, excluding IgxInput. More detailed information about this can be found in the Label & Input topic.

    In the default configuration, a dropdown/dialog toggle icon is shown as a prefix. It can be changed or redefined using the IgxPickerToggleComponent component. It can be decorated with either igxPrefix or igxSuffix, which will define its position - at the start of the input or at the end respectively.

    다음 예에서는 사용자 정의 레이블과 힌트를 추가하고 접미사로 표시되도록 기본 토글 아이콘 위치를 변경했습니다.

    <igx-time-picker [(ngModel)]="date" mode="dialog" [inputFormat]="'hh:mm'">
        <label igxLabel>Home Time </label>
        <igx-picker-toggle igxSuffix>
            <igx-icon>home</igx-icon>
        </igx-picker-toggle>
        <igx-hint>{{date.toLocaleString()}}</igx-hint>
    </igx-time-picker>
    
    public date: Date = new Date();
    

    Ignite UI for Angular 다음과 같습니다.

    Custom action buttons

    The IgxTimePickerComponent supports action button customization. To achieve that, wrap the buttons in ng-template marked with the igxPickerActions directive selector.

    아래 예에서는 'CANCEL', 'DONE' 및 'NOW' 작업에 대한 사용자 정의 작업 버튼이 추가되었습니다.

    <!-- sample.component.html -->
    
    <igx-time-picker #picker format="hh:mm" mode="dropdown">
        <ng-template igxTimePickerActions>
            <div class="container action-buttons">
                <button igxButton="flat" (click)="picker.cancelButtonClick()">cancel</button>
                <button igxButton="flat" (click)="picker.okButtonClick()">done</button>
                <button igxButton="flat" (click)="selectNow(picker)">now</button>
            </div>
        </ng-template>
    </igx-time-picker>
    
    // sample.component.ts
    ...
    public selectNow(timePicker: IgxTimePickerComponent) {
        timePicker.value = new Date();
        timePicker.close();
    }
    ...
    

    드롭다운, 사용자 지정 작업 및 양방향 바인딩 지원을 포함하는 템플릿이 다시 지정된 시간 선택기가 있습니다.

    Customizing the toggle and clear icons

    The IgxTimePickerComponent 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-time-picker>
        <label igxLabel>Select time</label>
        <igx-picker-toggle igxPrefix>
            <igx-icon>snooze</igx-icon>
        </igx-picker-toggle>
        <igx-picker-clear igxSuffix>
            <igx-icon>delete</igx-icon>
        </igx-picker-clear>
    </igx-time-picker>
    

    Keyboard Navigation

    • Users can navigate the component's time portions via the keyboard Up and Down arrow keys or by scrolling in the input field and in the dropdown/dialog. Navigation in the input is possible regardless of the minValue or maxValue, while navigation in the dropdown/dialog will be restricted within the minValue and maxValue range.
    • 시간 선택기 드롭다운은 토글 아이콘 클릭, 스페이스 키 또는 Alt + 아래쪽 키를 눌러 열 수 있습니다. 대화 상자 모드에서는 입력 클릭으로 이를 수행할 수 있습니다.
    • 드롭다운/대화상자 외부에서 Enter 키를 누르거나 마우스를 클릭하면 선택 사항이 적용되고 드롭다운/대화상자가 닫힙니다.
    • Esc 키를 누르면 선택이 취소되고 드롭다운/대화 상자가 닫힙니다.
    • 드롭다운이 닫혀 있는 동안 새 값을 입력하면 시간 선택기 외부를 클릭하거나 Tab 키를 눌러 값이 적용되도록 포커스를 이동합니다.

    Examples

    Dialog Mode

    The default time picker mode is editable dropdown mode. To change the time picker mode to read-only dialog mode, set the mode input to dialog:

    // timePickerDropdown.component.ts
    
    import { PickerInteractionMode } from 'igniteui-angular';
    // import { PickerInteractionMode } from '@infragistics/igniteui-angular'; for licensed package
    ...
    public mode = PickerInteractionMode.Dialog;
    
    <!--timePickerDropdown.component.html-->
    <igx-time-picker [mode]="mode"></igx-time-picker>
    

    or just change the mode in the time picker like this:

    <!--timePickerDropdown.component.html-->
    <igx-time-picker mode="dialog"></igx-time-picker>
    

    In dialog mode, the dialog header displays the currently selected time in the picker's input format. You can change the header position by setting the headerOrientation property.

    When the minValue and maxValue are set the dialog displays the time within that range only. See the Min max value example below, for more details.

    Display and input format

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

    The display format is the format of the value when in edit mode and can be one of the listed Angular DatePipe formats. This allows it to support predefined format options, such as shortTime and longTime.

    The input format is the format of the value when not in edit mode and the format, in which the time portions are displayed in the dropdown/dialog. The inputFormat property accepts a constructed format string using characters supported by the DatePipe, e.g. hh:mm:ss, but doesn't support predefined format options, such as shortTime and longTime. If the inputFormat property is not defined, it defaults to hh:mm tt. 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.

    <igx-time-picker
        [(ngModel)]="time"
        [inputFormat]="`hh:mm:ss`"
        [displayFormat]="`shortTime`">
    </igx-time-picker>
    
    Note

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

    Increment and decrement

    The time picker exposes public increment and decrement methods, which accept two optional parameters: the DatePart to be modified and the delta by which it will be changed. If not specified the DatePart defaults to Hours and the delta defaults to itemsDelta.

    Date Time Editor Directive에서 두 방법의 사용을 보여주는 샘플을 찾을 수 있습니다.

    Forms and Validation

    시간 선택기 구성 요소는 핵심 FormsModule NgModelReactiveFormsModule (FormControl, FormGroup 등)의 모든 지시문을 지원합니다. 여기에는 양식 유효성 검사기 기능도 포함됩니다. 또한 구성 요소의 최소 및 최대 값은 양식 유효성 검사기 역할도 합니다.

    Reactive Forms Integration 샘플은 Reactive Forms에서 igxTimePicker를 사용하는 방법을 보여줍니다.

    최소 최대 값

    You can specify minValue and maxValue to restrict the user input, in which case the dropdown/dialog will display the time within that range only. In dropdown mode however, it is still possible for the user to type in an invalid time. You can handle the validationFailed event in order to notify the user if that happens.

    Note

    The min/max values should be a Date object or a time-only string in the ISO 8601 format:

    // app.module.ts
    
    ...
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { IgxTimePickerModule, IgxToastModule } from 'igniteui-angular';
    // import { IgxTimePickerModule, IgxToastModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        ...
        imports: [..., BrowserAnimationsModule, IgxTimePickerModule, IgxToastModule],
        ...
    })
    export class AppModule {}
    
    // app.component.ts
    
    public time = '10:00:00';
    public min = '09:15:30';
    public max = '18:15:30';
    
    @ViewChild('toast', { static: true })
    private toast;
    
    public onValidationFailed() {
        this.toast.open();
    }
    
    <igx-time-picker
     [(ngModel)]="time"
        [itemsDelta]="{hours:2, minutes:5}"
        [inputFormat]="'hh:mm:ss tt'"
        [headerOrientation]="true"
        [minValue]="min"
        [maxValue]="max"
     (onValidationFailed)="onValidationFailed()">
     <label igxLabel>Meeting Start</label>
    </igx-time-picker>
    
    <igx-toast #toast message="Value must be between 09:15:30 AM and 06:15:30 PM"></igx-toast>
    
    

    드롭다운에는 항목 델타를 기준으로 최소/최대 범위(09:15:30 AM~06:15:30 PM) 내의 값이 표시됩니다. 잘못된 시간을 입력했을 때 메시지를 표시하기 위해 토스트가 추가됩니다.

    Note

    The displayed values for each time portion in the dropdown/dialog are calculated based on the items delta always starting from zero. If the minValue and maxValue does not match the items delta, the displayed values will start/end from the next/last possible value that matches the threshold.

    그리고 거기에 우리는 그것을 가지고 있습니다:

    날짜 및 시간 선택기를 함께 사용

    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.

    스타일링

    To get started with styling the time 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';
    

    Following the simplest approach, we create a new theme that extends the time-picker-theme and accepts parameters that style the time picker.

    $my-time-picker-theme: time-picker-theme(
      $text-color: #e4c8a5,
      $hover-text-color: #ecaa53,
      $selected-text-color: #ecaa53,
      $header-background: #ecaa53,
      $background-color: #011627
    );
    
    Note

    In order to style any additional components that are used as part of the time picker window's content (such as the IgxButton), an additional theme should be created that is specific to the respective component and is placed under the dialog window's scope only (so it does not affect the rest of the application).

    Since the time picker window uses the IgxOverlayService, in order for our custom theme to reach down the time picker window that we want to style, we will provide a specific outlet where the dialog window will be placed in the DOM when it is visible.

    The items in our time picker are not descendants of our component host - they are currently being displayed in the default overlay outlet, at the end of the document body. Changing this is done by making use of the outlet property in the overlaySettings. The outlet controls where the overlay container should be rendered.

    여기에서 컨테이너를 배치할 요소에 대한 참조를 전달할 수 있습니다.

    <igx-time-picker #picker [overlaySettings]="{ outlet: element }">
    </igx-time-picker>
    
    export class TimepickerStylingComponent {
        constructor(public element: ElementRef) {
        }
    }
    

    이제 시간 선택기의 항목이 구성 요소의 호스트 내부에 올바르게 렌더링되므로 사용자 정의 테마가 적용됩니다.

    Note

    보여준 요소IgxOverlayService에 테마를 제공하는 다양한 옵션에 대해 더 알고 싶다면, 오버레이 스타일링 주제를 살펴보세요.

     @include css-vars($my-time-picker-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($my-time-picker-theme);
      }
    }
    

    Demo

    API References

    Theming Dependencies

    Additional Resources

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