【问题标题】:How to get selected value of Material DatePicker from component.ts如何从 component.ts 中获取 Material DatePicker 的选定值
【发布时间】:2019-05-16 19:10:02
【问题描述】:

我有一个 html 文件形式的日期选择器。提交表单后,我需要在我的 component.ts 文件中获取日期选择器的选定值

在 html 文件中:

<form (ngSubmit)="onSubmit(f)" #f="ngForm">
<input type="text" class="datepicker" ngModel id ="from" name="from" placeholder="From :"> 
</form>

in the component.ts file:
console.log(f.value.from); 

我试过上面的代码,得到的值是未定义的。

【问题讨论】:

标签: angular angular-material


【解决方案1】:

添加 [(ngModel)]

<input type="text" class="datepicker" [(ngModel)]="from" id ="from" name="from" placeholder="From:">

并在 .ts 中声明

public from;

那么它应该可以在 onSubmit 函数中使用

【讨论】:

  • 仍然得到未定义的值
【解决方案2】:

查看此堆栈闪电战

https://stackblitz.com/edit/angular-dcr7ub

注意[(ngModel)]="date" 表单中的双向绑定链接到app.component.ts 中的date,尽管您可以使用反应式表单来做到这一点。

app.component.html

<form (ngSubmit)="onSubmit()" #f="ngForm">
  <div class="example-container">
  Form
    <mat-form-field>
      <input matInput [(ngModel)]="date" [matDatepicker]="picker" name="date" placeholder="Choose a date" />
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
      </mat-form-field>
 </div>

  <button type="submit" class="btn btn-success">Submit</button>
</form>

在实现这一点时我遇到了一些棘手的事情:

import {MatDatepickerModule} from '@angular/material/datepicker';
import {MatFormFieldModule, MatInputModule} from '@angular/material';
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import { MatMomentDateModule } from "@angular/material-moment-adapter";

最后一个是你必须提供一个DateAdapter 来处理日期(日期选择器对此是不可知的)。

  • 记得在styles.css中加入一个主题,我用过:
@import '@angular/material/prebuilt-themes/deeppurple-amber.css';

所以在我的示例中,日期是一个时刻 (https://momentjs.com/) 对象,因此 .format() 在:

  onSubmit() {
    console.log((<any>this.date).format());
  }

【讨论】:

    猜你喜欢
    • 2021-06-16
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    相关资源
    最近更新 更多