我从Angular开始,试图制作一个简单的应用程序只是为了学习如何使用它。 我想做的是从mat-select中获取一个值,并根据选择更改mat-datepicker的掩码。
当前在我的代码中,它显示所需的数据,但我需要在代码中手动进行更改。
示例:用户选择dd mmm yyyy,并且mat-datepicker会显示用户选择的内容,而不是显示dd / mm / yyyy
问题是: 如何根据垫选上设置的选项动态更改日期选择器的掩码?
我的HTML
<h4>Please select a date format</h4>
<mat-form-field>
<mat-select placeholder="Date Format" [(value)]="selected">
<mat-option *ngFor="let dateformats of dateformatArray" [value]="dateformats.value">
{{dateformats.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-card>
<mat-card-title>Date Picker validator</mat-card-title>
<mat-card-content>
<mat-form-field>
<input matInput placeholder="Valid Date" [min]="minDate" [matDatepicker]="dateValid" [formControl]="dateCtrl">
<mat-datepicker-toggle matSuffix [for]="dateValid">
</mat-datepicker-toggle>
<mat-datepicker #dateValid></mat-datepicker>
<mat-error align="end" *ngIf="dateCtrl.hasError('required')">
A valid date format is required
</mat-error>
</mat-form-field>
</mat-card-content>
</mat-card>
app.components.ts
import { Component, OnInit, Input, Output, forwardRef, EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor, FormControl, Validators } from '@angular/forms';
import { MomentDateAdapter } from '@angular/material-moment-adapter';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material';
export const MY_FORMATS = {
parse: {
dateInput: 'DD MMM YYYY',
},
display: {
dateInput: 'DD MMM YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }
],
})
export class AppComponent {
title = 'material-ng';
selected = "string:DD_MMM_YYYY";
myDate : Date = new Date();
export interface dateformatlist {
value: string;
viewValue: string;
}
dateformatArray: dateformatlist[] = [
{value: 'string:DD_MMM_YYYY', viewValue: 'dd MMM yyyy'},
{value: 'string:DDMMMYY', viewValue: 'ddMMMyy'},
{value: 'string:YYYY_MMM_DD', viewValue: 'yyyy MMM dd'},
{value: 'string:MMM_DD_YYYY', viewValue: 'MMM dd yyyy'},
{value: 'string:YYYY_MM_DD', viewValue: 'yyyy-MM-dd'},
{value: 'string:DD_MM_YYYY', viewValue: 'dd.MM.yyyy'},
];
minDate = new Date();
dateCtrl:FormControl;
constructor() {}
ngOnInit(){
this.dateCtrl = new FormControl('', [Validators.required])
}
}
谢谢!