如何使用nameFormControl从datepicker angular-material和Reactive Form格式化日期?角度6

时间:2019-12-05 19:33:27

标签: angular datepicker angular-material

无法格式化日期。无论我想给我这个日期“ 2019-12-11T23:00:00.000Z”还是以正确的格式返回当前日期。最大的问题是我不知道在哪里格式化日期。我想要像“ Y-MM-DD”这样的日期。看我的代码:

export const MY_FORMATS = {
  parse: {
    dateInput: 'Y-MM-DD',
  },
  display: {
    dateInput: 'Y-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: [
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
    },

    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],
})




  ngOnInit() {  
    this.form = this.fb.group({
      deliveryDate: [moment().format('Y-MM-DD')] 
   // this is return mee full ISO date like a "2019-12-11T23:00:00.000Z"
    });



    <mat-form-field>
        <input formControlName="deliveryDate"  matInput [matDatepicker]="resultOfdate" placeholder="Izaberite datum isporuke" (dateInput)="first($event.value.format('YYYY-MM-D'))"  >
        <mat-datepicker-toggle matSuffix [for]="resultOfdate" ></mat-datepicker-toggle>
        <mat-datepicker #resultOfdate></mat-datepicker>
      </mat-form-field>

我还具有再次获取日期查找模板的功能(上图):

(dateInput)="first($event.value.format('YYYY-MM-D'))"

以及当我console.log时:

  first(e) {
    console.log("EE" , e );
    this.resultOfdate = e;
    //this is return me real date but when i pass this this.resultOfdate my control like a 

    this.form = this.fb.group({
      deliveryDate: [this.resultOfdate]
})

再次:交货日期:“ 2019-12-21T23:00:00.000Z”

我尝试了一切,但没有成功。 我已经读过一些适配器,如果它们对我来说比当前适配器更复杂,我将不使用它们。

1 个答案:

答案 0 :(得分:0)

struct TestScrollInList: View {
    var body: some View {
        List {
            ForEach (0..<20, id: \.self) { i in
                self.rowItem(index: i)
            }
        }
    }

    func rowItem(index i: Int) -> AnyView {
        if i % 2 == 0 {
            return AnyView(self.plainItem(index: i))
        } else {
            return AnyView(self.scrollableItem(index: i))
        }
    }

    func plainItem(index i: Int) -> some View {
        Text("Plain item \(i)")
    }

    func scrollableItem(index i: Int) -> some View {
        ScrollView (.horizontal, showsIndicators: false) {
            HStack {
                ForEach(0..<10) { j in
                    RoundedRectangle(cornerRadius: 8)
                        .fill(j % 2 == 0 ? Color.green : Color.yellow)
                        .frame(width: 100, height: 100)
                }
            }
        }
        .frame(maxHeight: 110)
    }
}

struct TestScrollInList_Previews: PreviewProvider {
    static var previews: some View {
        TestScrollInList()
    }
}