source

각도-소재 날짜/시간 선택기 구성요소?

ittop 2023. 9. 24. 13:07
반응형

각도-소재 날짜/시간 선택기 구성요소?

프로젝트에서 날짜 선택기를 가져왔는데 달력에 시간을 포함할 수 있는 각도와 재질의 공식적인 최근 구성요소가 있는지 궁금합니다.
자료 문서에서 많은 시간 선택자를 보았고 제3자의 시간 선택자를 많이 조사했지만 매우 복잡해 보입니다.

를 할 때 할 수 .matInputdatetime-local다음과 같습니다.

  <mat-form-field>
    <input matInput type="datetime-local" placeholder="start date">
  </mat-form-field>

자리 표시자의 각 부분을 클릭하여 일, 월, 년, 시간, 분 및 AM 또는 PM 중 어느 것을 선택할 수 있습니다.

@angular-material-components/datetime-picker를 확인하는 것을 추천합니다.@angular/material Datepicker와 같은 DatetimePicker로 시간선택 지원을 추가하였습니다.

enter image description here

각도 자체에서 공식적인 날짜 및 시간 선택기가 없는 한 기본 각도 날짜 선택기와각도 재료 시간 선택기의 조합을 만드는 것이 좋습니다.이 때 발견한 다른 것들은 모두 문제에 대한 지원이 부족하거나 최신 각도 버전에서 제대로 작동하지 않기 때문에 선택한 것입니다.이 사람은 굉장히 반응이 좋은 것 같습니다.

하나의 단위처럼 보이도록 두 개를 모두 하나의 부품으로 포장했습니다.몇 가지만 확실히 하면 됩니다.

아직 입력 사항이 주어지지 않았을 때는 다음과 같이 조언합니다.

  • 구성 요소를 클릭하면 항상 날짜 선택기가 먼저 트리거되어야 합니다.
  • 날짜 선택기가 닫히면 자동으로 시간 선택기 팝업이 나타납니다.
  • 사용하다touchUi = true날짜 선택기에서 날짜 선택기와 시간 선택기가 서로 대화 상자로 오도록 합니다.
  • 양식을 클릭할 때(기본 아이콘에만 표시되는 것이 아니라) 날짜 선택기도 나타나는지 확인합니다.
  • 솔루션을 사용하여 타임피커를 재료 형태로도 사용할 수 있습니다. 타임피커를 서로 뒤에 두었을 때는 하나의 형태로 보입니다.

값이 지정된 후 한 부분에는 시간이 포함되고 다른 부분에는 날짜가 포함되는 것이 분명합니다.그 순간 사용자가 시간을 변경하려면 시간을 클릭해야 하고 날짜를 변경하려면 날짜를 클릭해야 하는 것이 분명합니다.그러나 그 전에 두 필드가 모두 비어 있고(그리고 하나의 필드로 서로 '첨부'되어 있을 때) 위의 권장 사항을 수행하여 사용자가 혼동하지 않도록 해야 합니다.

제 부품이 아직 완성되지 않았습니다. 나중에 코드를 공유할 수 있도록 기억하겠습니다.이 질문이 한 달 이상 지난 질문이면 댓글을 달아주세요.

편집: 결과

enter image description here

<div fxLayout="row">
  <div *ngIf="!dateOnly" [formGroup]="timeFormGroup">
    <mat-form-field>
      <input matInput [ngxTimepicker]="endTime" [format]="24"  placeholder="{{placeholderTime}}" formControlName="endTime" />
    </mat-form-field>
    <ngx-material-timepicker #endTime (timeSet)="timeChange($event)" [minutesGap]="10"></ngx-material-timepicker>
  </div>
  <div>
    <mat-form-field>
      <input id="pickerId" matInput [matDatepicker]="datepicker" placeholder="{{placeholderDate}}" [formControl]="dateForm"
             [min]="config.minDate" [max]="config.maxDate" (dateChange)="dateChange($event)">
      <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
      <mat-datepicker #datepicker [disabled]="disabled" [touchUi]="config.touchUi" startView="{{config.startView}}"></mat-datepicker>
    </mat-form-field>
  </div>
</div>
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { DateAdapter, MatDatepickerInputEvent } from '@angular/material';

import * as moment_ from 'moment';

const moment = moment_;

import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';

class DateConfig {
  startView: 'month' | 'year' | 'multi-year';
  touchUi: boolean;
  minDate: moment_.Moment;
  maxDate: moment_.Moment;
}

@Component({
  selector: 'cb-datetimepicker',
  templateUrl: './cb-datetimepicker.component.html',
  styleUrls: ['./cb-datetimepicker.component.scss'],
})
export class DatetimepickerComponent implements OnInit {

  @Input() disabled: boolean;
  @Input() placeholderDate: string;
  @Input() placeholderTime: string;
  @Input() model: Date;
  @Input() purpose: string;
  @Input() dateOnly: boolean;

  @Output() dateUpdate = new EventEmitter<Date>();

  public pickerId: string = "_" + Math.random().toString(36).substr(2, 9);

  public dateForm: FormControl;
  public timeFormGroup: FormGroup;
  public endTime: FormControl;

  public momentDate: moment_.Moment;
  public config: DateConfig;

  //myGroup: FormGroup;


  constructor(private adapter : DateAdapter<any>) { }

  ngOnInit() {

    this.adapter.setLocale("nl-NL");//todo: configurable
    this.config = new DateConfig();
    if (this.purpose === "birthday") {
      this.config.startView = 'multi-year';
      this.config.maxDate = moment().add('year', -15);
      this.config.minDate = moment().add('year', -90);
      this.dateOnly = true;
    } //add more configurations
    else {
      this.config.startView = 'month';
      this.config.maxDate = moment().add('year', 100);
      this.config.minDate = moment().add('year', -100);
    }


    if (window.screen.width < 767) {
      this.config.touchUi = true;
    }



    if (this.model) {
      var mom = moment(this.model);
      if (mom.isBefore(moment('1900-01-01'))) {
        this.momentDate = moment();
      } else {
        this.momentDate = mom;
      }
    } else {
      this.momentDate = moment();
    }

    this.dateForm = new FormControl(this.momentDate);
    if (this.disabled) {
      this.dateForm.disable();
    }
    this.endTime = new FormControl(this.momentDate.format("HH:mm"));

    this.timeFormGroup = new FormGroup({
      endTime: this.endTime
    });


  }


  public dateChange(date: MatDatepickerInputEvent<any>) {

    if (moment.isMoment(date.value)) {
      this.momentDate = moment(date.value);
      if (this.dateOnly) {
        this.momentDate = this.momentDate.utc(true);
      } 
      var newDate = this.momentDate.toDate();
      this.model = newDate;
      this.dateUpdate.emit(newDate);
    }

    console.log("datechange",date);
  }

  public timeChange(time: string) {

    var splitted = time.split(':');
    var hour = splitted[0];
    var minute = splitted[1];

    console.log("time change", time);
   this.momentDate = this.momentDate.set('hour', parseInt(hour));
    this.momentDate = this.momentDate.set('minute', parseInt(minute));

    var newDate = this.momentDate.toDate();
    this.model = newDate;
    this.dateUpdate.emit(newDate);
  }
}

한가지 중요한 출처: https://github.com/Agranom/ngx-material-timepicker/issues/126

이것을 만드는 데 시간이 더 많이 걸릴 때 조금 더 효과적일 수 있다고 생각하기 때문에 아직도 약간의 수정이 필요하다고 생각합니다.가장 중요한 것은 UTC 문제도 해결하려고 노력했기 때문에 모든 날짜는 현지 시간으로 표시되어야 하지만 UTC 형식으로 서버에 전송되어야 합니다(또는 적어도 정확한 시간대가 추가되어 저장되어야 합니다).

안타깝게도, 시간 선택을 위한 공식 머티리얼 지원이 있는지에 대한 질문에 대한 답은 "아니오"이지만, 현재 머티리얼2 GitHub 공식 repo: https://github.com/angular/material2/issues/5648 에서 공개된 이슈입니다.

이것이 곧 바뀌기를 바랍니다. 그 사이에 이미 발견한 제3자와 싸워야 할 것입니다.GitHub 문제에는 시도해 볼 수 있는 자체적인 해결책을 제공하는 사람들이 몇 명 있습니다.

현재 Angular Team을 상대로 4년 전부터 시간 및 날짜 선택기 지원을 요청하는 공식 오픈 이슈가 있습니다. https://github.com/angular/components/issues/5648

이 게시물에서 볼 수 있듯이 많은 라이브러리가 있습니다. 문제는 대부분의 라이브러리가 더 이상 사용되지 않는다는 것입니다(구 Angular 버전).

@mathheo의 이 제품을 실제로 사용하고 있습니다. 제가 발견한 것 중 가장 최근에 유지보수된 제품입니다.

https://www.npmjs.com/package/ @최근 https://www.npmjs.com/package/ @matheo/데이트피커로 이동한 coach케어


데모: http://matheo.co/demos/datepicker



참고: Angular version >= 12에서 작동하지 않는 경우 새 Angular convention 테마가 사용되고 있는지 확인하십시오. 예:

@use "~@matheo/datepicker/theming" as datepicker;
// ...
@include datepicker.mat-datepicker-theme($main_theme);

Date&Time 제어를 구현하는 가장 좋은 방법은 "datetime-local" 입력 유형을 사용하는 것입니다.https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local 을 참조해 주시기 바랍니다.

샘플코드는

<mat-grid-list [cols]="5" gutterSize="20px" rowHeight="70px">
                <form *ngIf="dateForm && dateForm !== null" [formGroup]="dateForm">
                    <mat-grid-tile>
                        <mat-form-field appearance="outline" floatLabel="auto">
                            <mat-label>From Date</mat-label>
                            <input type="datetime-local" matInput name="fromTime" formControlName="fromDate">
                        </mat-form-field>
                    </mat-grid-tile>
                    <mat-grid-tile>
                        <mat-form-field appearance="outline" floatLabel="auto">
                            <mat-label>To Date</mat-label>
                            <input type="datetime-local" matInput name="toTime" formControlName="toDate">
                        </mat-form-field>
                    </mat-grid-tile>
                </form>
</mat-grid-list>

각진 소재의 익스텐션을 사용하는 것이 좋을 것 같습니다.매우 유용한 것 같습니다. https://ng-matero.github.io/extensions/components/datetimepicker/overview

는 당신에게 https://vlio20.github.io/angular-datepicker/ 을 확인해 볼 것을 제안합니다.

enter image description here

다른 방법 사용: 매트-데이트 픽커-액션

{{label}}
    <mat-datepicker #picker>
      <mat-datepicker-actions>
        <input [ngxTimepicker]="pickerTime">
        <ngx-material-timepicker #pickerTime></ngx-material-timepicker>
      </mat-datepicker-actions>
    </mat-datepicker>
  </mat-form-field>

enter image description here

언급URL : https://stackoverflow.com/questions/48649987/angular-material-datetime-picker-component

반응형