【问题标题】:How to initialize an Angular Material Datepicker input form field?如何初始化 Angular Material Datepicker 输入表单域?
【发布时间】:2019-12-01 18:11:47
【问题描述】:

我正在尝试格式化我的日期选择器。我不知道路。我尝试插入一个我不知道如何使用但从 Internet 复制的 moment.js 库。现在我的日期选择器返回一个对象时刻,我不知道如何格式化它。

组件

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>

【问题讨论】:

    标签: angular datepicker angular-material


    【解决方案1】:

    Angular Material Datepicker 设置初始日期的最简单方法是在构造表单控件时设置初始日期值。

    组件

    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>
    

    结果表格

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-27
      • 2018-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 2018-03-28
      • 2019-08-20
      相关资源
      最近更新 更多