简体   繁体   English

如何初始化 Angular Material Datepicker 输入表单字段?

[英]How to initialize an Angular Material Datepicker input form field?

I'm trying to format my date picker.我正在尝试格式化我的日期选择器。 I don't know the way.我不知道路。 I tried inserting a moment.js library that I don't know how to use but copying it from the internet.我尝试插入一个我不知道如何使用但从互联网上复制它的 moment.js 库。 Now my date picker returns an object moment and I don't know how to format this.现在我的日期选择器返回一个对象时刻,我不知道如何格式化它。

Component成分

this.form = this.fb.group({
  deliveryDate: [this.deliveryDate], // i try to set here instead this.delieryDate null or moment() or everythink.....
  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()])
});

Template模板

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Izaberite datum narudzbe"
      formControlName="deliveryDate">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

The simplest way to set the initial date for an Angular Material Datepicker is to set an initial date value when constructing the form control.Angular Material Datepicker设置初始日期的最简单方法是在构造表单控件时设置初始日期值。

Component成分

import {Component} from '@angular/core';
import {FormBuilder, FormControl, Validators} from '@angular/forms';

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  deliveryForm = this.fb.group({
    deliveryDate: [new Date()],
    address: [null, [Validators.required, Validators.minLength(5)]],
    phone: [null, [Validators.minLength(9),Validators.maxLength(19)]],
    city: [null, [Validators.required, Validators.minLength(5)]]
  });

  constructor(private fb: FormBuilder) { }
}

HTML Template HTML模板

<form [formGroup]="deliveryForm">
  <mat-form-field>
    <input matInput [matDatepicker]="picker" placeholder="Izaberite datum narudzbe"
         formControlName="deliveryDate">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
  </mat-form-field>

  <mat-form-field>
    <input matInput formControlName="address" placeholder="Address"
      autocomplete="address-line1">
  </mat-form-field>

  <mat-form-field>
    <input matInput formControlName="phone" placeholder="Phone number"
      autocomplete="tel-national">
  </mat-form-field>

  <mat-form-field>
    <input matInput formControlName="city" placeholder="City" autocomplete="address-level2">
  </mat-form-field>
</form>

Resulting Form结果表格

带有日期选择器的示例表单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM