[英]How to format date from date picker angular material in format ('Y-MM-DD')? Reactive form
我已经尝试了一切,但我没有成功。 在我不做反应式而是 ng-model 的例子中,对我来说很容易:
deliveryDate: moment(this.startDate).format('Y-MM-DD')
但是在 Angular 形式的当前代码中,我无法改变任何东西。 看我的代码:
export const MY_FORMATS = {
parse: {
dateInput: 'MM/DD',
},
display: {
dateInput: 'MM/DD',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
@Component({
selector: 'app-my-order',
templateUrl: './my-order.component.html',
styleUrls: ['./my-order.component.scss'],
providers: [
// `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your
// application's root module. We provide it at the component level here, due to limitations of
// our example generation script.
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
],
})
resultOfdate: any = MY_FORMATS;
this.getProducts();
this.form = this.fb.group({
deliveryDate: [moment(this.resultOfdate).format('2020-MM-DD'), Validators.required], //this is not work format is hard-code on 2020 because deliveryDate from form return current date like a new Date(). this.resultOfdata is
address: [null, [Validators.required, Validators.minLength(5)]],
phone: [null, [Validators.minLength(9),Validators.maxLength(19)]],
city: [null, [Validators.required, Validators.minLength(5)]],
data: this.fb.array([this.createContact()]),
note: [null]
});
还有我的模板:
<mat-form-field>
<input formControlName="resultOfdate" matInput [matDatepicker]="resultOfdate" placeholder="Choose a date" >
<mat-datepicker-toggle matSuffix [for]="resultOfdate" ></mat-datepicker-toggle>
<mat-datepicker #resultOfdate></mat-datepicker>
</mat-form-field>
我想发送一个 2019-10-10 的例子
您可能在错误的地方使用了 moment.format。
像这样尝试,像这样在 dateChange 上调用你的方法:
export const MY_FORMATS_ORG = {
parse: {
dateInput: 'MM/DD',
},
display: {
dateInput: 'MM/DD',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
@Component({
selector: 'datepicker-formats-example',
templateUrl: 'datepicker-formats-example.component.html',
styleUrls: ['datepicker-formats-example.component.css'],
providers: [
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS_ORG},
],
})
export class DatepickerFormatsExampleComponent {
date = new FormControl(moment());
dateData: string;
public setDate(date: string) {
this.dateData = date ? moment(date).format('Y-MM-DD') : '';
}
}
在这里查看: https : //stackblitz.com/edit/angular-material-datepicker-6hjuhq?file=src/app/app.component.ts
还有这个:
deliveryDate: moment(this.startDate).format('Y-MM-DD')
会错,应该是这样的:
deliveryDate: string;
并且分配将在方法中完成。
我希望它有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.