如何在角度日期选择器中设置日期格式

时间:2020-05-12 21:41:16

标签: angular datepicker mat-datepicker

我有一个表单,其中包含一个表单控件作为日期选择器和一个mat日期选择器。当我使用日期纠察器选择日期时,表单控件将采用日期类。我需要将其转换为字符串。请在这方面帮助我 html代码:

<mat-form-field appearance="fill">
                <input matInput [matDatepicker]="picker" formControlName="date" placeholder="Choose a date">
                <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                <mat-datepicker #picker></mat-datepicker>
            </mat-form-field>

当我选择一个日期时,应将其转换为11-05-2020(dd-mm-yyyy)作为提交时的表单控件。 请帮助我

编辑:

 import { Component, OnInit } from '@angular/core';
    import { ProductsService } from '../products/products.service';
    import { forkJoin } from 'rxjs';
    import { FormControl, Validators, FormBuilder, FormArray } from '@angular/forms';
    import { Router } from '@angular/router';
    import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';

    @Component({
      selector: 'app-orders',
      templateUrl: './orders.component.html',
      styleUrls: ['./orders.component.scss'],
      providers: [ProductsService, {provide: MAT_DATE_LOCALE, useValue: 'en-GB'}]
    })
    export class OrdersComponent implements OnInit {
       paginationPageSize:any;
       getRowHeight:any;
    statusList=['open','closed'];
    form = this.fb.group({

      city: new FormControl('', Validators.required),
      date: new FormControl('', Validators.required),
      status: new FormControl('', Validators.required),
      pageNum:0,
      pageSize:10,
      preOrders: new FormControl(false, Validators.required),
     });
     constructor(private productsService: ProductsService, private fb: FormBuilder, private router: Router) { }

      ngOnInit() {
      }

      onSubmit() {
        if (this.form.valid) {
          const value = this.form.value;
        }
    }


    }

我已经添加了提供程序,但仍然无法正常工作。

1 个答案:

答案 0 :(得分:0)

您可以使用国际化语言环境更改日期格式

在组件TS中设置区域设置...

@Component({
  selector: ...,
  templateUrl: ...,
  styleUrls: ...,
  providers: [
    {provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
  ],
  ...
})
export class Component ...

如果要全局更改它,请在app.module.ts

中设置区域设置。
@NgModule({
  providers: [
    {provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
  ],
})
export class AppModule {}

参考:https://material.angular.io/components/datepicker/overview#internationalization

希望有帮助!