如何初始化Angular Material Datepicker输入表单字段? [英] How to initialize an Angular Material Datepicker input form field?

查看:238
本文介绍了如何初始化Angular Material Datepicker输入表单字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化日期选择器.我不知道我试图插入一个我不知道如何使用的moment.js库,但是要从互联网上复制它.现在我的日期选择器返回一个对象时刻,我不知道该如何格式化.

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. Now my date picker returns an object moment and I don't know how to format this.

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()])
});

模板

<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>

推荐答案

设置角度材料Datepicker 用于在构造表单控件时设置初始日期值.

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.

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模板

<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>

结果表格

这篇关于如何初始化Angular Material Datepicker输入表单字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆