直接使用mat-datepicker,无需输入

问题描述 投票:0回答:4

我想将日期选择器放在永久可见的侧边栏中,并且不依赖于输入,这可能吗? 我想象只需放置组件并添加opened = true就可以使日期选择器在盒子内始终可见。

angular angular-material2
4个回答
39
投票

事实证明,这非常简单,照常导入 MatDatePickerModule,然后只需使用 mat-calendar 选择器

<mat-calendar></mat-calendar>

为了通过打字稿挂钩选择

  @ViewChild(MatCalendar) _datePicker: MatCalendar<Date>

ngOnInit() {
    this._datePicker.selectedChange.subscribe(x => {
      console.log(x);
    });
  }

25
投票

你也可以尝试用css隐藏 ex:

<mat-form-field style="width:1px;visibility:hidden;">
  <input matInput [matDatepicker]="picker" >
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<button mat-button (click)="picker.open()" ></button>

使用 css 隐藏的优点是日期选择器相对于隐藏的表单字段定位


0
投票

您可以避免使用日期选择器组件,而只需在用户单击您想要的任何位置时使用日历来选择日期。

turbogui-Angular 开源库以超级易用的方式封装了 mat-calendar 组件。首先将其安装到您的项目中:

npm install turbogui-angular

然后在需要的地方导入dialogService并调用addDateSelectionDialog:

import { DialogService } from 'turbogui-angular';

// Inject the required dialog service into your angular component
constructor(public dialogService: DialogService) {

}

// Call for the calendar date picker
this.dialogService.addDateSelectionDialog({
        width: '500px',
        title: "some title for the calendar dialog"
    }, (selectedDate) => {

    if(selectedDate !== null){

        console.log(selectedDate);
    }
});

将出现 mat-calendar 组件并让用户选择日期。

更多信息在这里:

https://turboframework.org/en/blog/2024-02-19/easily-show-material-calendar-with-angular-to-pick-date


-1
投票

我发现的唯一有效方法是大且 borrrrrrrring 但有效:

部分学分

HTML

  <mat-form-field id="dashboardComponent">
    <input matInput
      [matDatepicker]="matDatepicker"
      [formControl]="dateFormControl"
      (dateChange)="onDateChanged('change', $event)"
      [max]="datePickerMaxDate"
      >
    <mat-datepicker-toggle matSuffix [for]="matDatepicker"></mat-datepicker-toggle>
    <mat-datepicker #matDatepicker></mat-datepicker>
  </mat-form-field>

组件.ts

@Component({
    ....
    encapsulation: ViewEncapsulation.None
})

export class MyComponent {

    // Date Picker
    public currentDate: Date = new Date() // set default here
    public dateFormControl: FormControl = new FormControl(this.currentDate)

CSS

/* DATE PICKER */
mat-form-field {
    margin: 0 0.5em; //adapt me to your needs
    width: 0.8em; //adapt me to your needs
    font-weight: normal;
}


#dashboardComponent {
    .mat-form-field-underline {
        background-color: transparent;
        height: 0;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.