我已经尝试了一切,但没有成功。在我不执行反应形式而是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的示例
答案 0 :(得分:0)
您可能在错误的地方使用了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;
,分配将在方法中完成。
希望对您有帮助。