【问题标题】:Angular date-picker without day selection (only month and year)没有日期选择的角度日期选择器(只有月份和年份)
【发布时间】:2021-12-15 01:51:45
【问题描述】:

我有问题。我想为 Angular 表单使用 date-picker,但我只需要选择 yearmonth,无需选择日期。这样做的简单方法是什么?另外我想知道如何将年份和月份分别写入.ts 文件。

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: angular datepicker


【解决方案1】:

您可以使用Angular Material DatePicker 解决此问题:

HTML:

<mat-form-field>
  <input #dpInput matInput [matDatepicker]="dp" placeholder="datepicker" [formControl]="date">
  <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
  <mat-datepicker #dp (monthSelected)="monthSelected($event, dp, dpInput)" startView="multi-year"></mat-datepicker>
</mat-form-field>

ts:

@Component({
  selector: 'datepicker-example',
  templateUrl: 'datepicker-example.component.html',
  styleUrls: ['datepicker-example.component.css'],
})
export class DatepickerFormatsExampleComponent {
  date = new FormControl(moment());

  monthSelected(event, dp, input) {
    dp.close();
    input.value = event.toISOString().split('-').join('/').substr(0, 7);
  }
}

monthSelected 函数将获取 datePicker 和输入引用,并将提取所选数据并设置输入值。


对于问题的另一部分,您可以使用monthSelectedyearSelected 事件,但它们会传递整个日期。您可以做的是通过以下方式提取这些日期对象的数量:

const array = event.toISOString().split('-');
const year = array[0];
const month = array[1];

【讨论】:

  • app.module.ts 导入 { MatDatepickerModule } from '@angular/material/datepicker';从“@angular/material/form-field”导入 { MatFormFieldModule };从“@angular/material/core”导入 { MatNativeDateModule };从“@angular/material/input”导入 { MatInputModule };导入:[ MatFormFieldModule, MatDatepickerModule, MatNativeDateModule, MatInputModule ],
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多