如何从component.ts获取材料DatePicker的选定值

时间:2019-05-16 19:10:03

标签: angular angular-material

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

在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); 


I have tried the above code and the value I get is undefined.

2 个答案:

答案 0 :(得分:0)

添加[(ngModel)]

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

在.ts中声明

public from;

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

答案 1 :(得分:0)

查看此堆叠闪电战

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

请注意,尽管可以使用反应形式,但以[(ngModel)]="date"形式的双向绑定链接到date中的app.component.ts

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());
  }
相关问题