【发布时间】:2018-10-06 09:45:13
【问题描述】:
我需要在一个组件视图的两个 mat datepicker 字段中选择两种不同的日期格式(YYYY-MM-DD 和 YYYY-MM)。
我正在使用角度 6.0.3 和材质 6.4.7。
我在应用程序模块中使用 MAT_DATE_FORMATS 将日期选择器格式配置为 YYYY-MM-DD,它可以在全局范围内使用,但我需要在上面写的几个日期选择器字段中将此格式覆盖为 YYYY-MM。 不幸的是,我不知道如何实现这一目标。
你能帮帮我吗?
我的部分代码:
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-invoice-list',
templateUrl: './invoice-list.component.html',
styleUrls: ['./invoice-list.component.css']
})
export class InvoiceListComponent {
filterForm: FormGroup;
@ViewChild('month_picker') month_picker;
constructor() {
this.filterForm = new FormGroup({
assigned_date_from: new FormControl(),
assigned_date_to: new FormControl(),
assigned_month: new FormControl(),
});
}
}
<div class="container" [formGroup]="filterForm">
<div class="container" fxLayout="row" fxLayout.xs="column" fxLayoutWrap fxLayoutGap="0.5%" fxLayoutAlign="start">
<div fxFlex="32%">
<mat-form-field>
<input matInput [matDatepicker]="date_from_picker" (focus)="date_from_picker.open()" formControlName="assigned_date_from" placeholder="Date from">
<mat-datepicker-toggle matSuffix [for]="date_from_picker"></mat-datepicker-toggle>
<mat-datepicker #date_from_picker></mat-datepicker>
</mat-form-field>
</div>
<div fxFlex="32%">
<mat-form-field>
<input matInput [matDatepicker]="date_to_picker" (focus)="date_to_picker.open()" formControlName="assigned_date_to" placeholder="Date to">
<mat-datepicker-toggle matSuffix [for]="date_to_picker"></mat-datepicker-toggle>
<mat-datepicker #date_to_picker></mat-datepicker>
</mat-form-field>
</div>
<!-- In below input I want month year format - YYYY-MM - so different than default format in above fields -->
<div fxFlex="32%">
<mat-form-field>
<input matInput [matDatepicker]="month_picker" (focus)="month_picker.open()" formControlName="assigned_month" placeholder="Month">
<mat-datepicker-toggle matSuffix [for]="month_picker"></mat-datepicker-toggle>
<mat-datepicker #month_picker></mat-datepicker>
</mat-form-field>
</div>
</div>
</div>
【问题讨论】:
-
你不能使用 viewChild 吗?
-
我考虑过 viewChild,但 viewChild 变量是为我视图中的所有日期选择器共享的,对吧?这样,此日期选择器(viewChild 变量)上组件的所有更改都将应用于我视图中的所有日期选择器字段
-
不,我可以帮你,但我需要一些时间。你能把你的 html 和 ts 文件放上去吗。
-
谢谢!!我在帖子中添加了部分代码
-
无需添加viewChildren。我会发布我的答案
标签: angular datepicker angular-material