我有一个以我的html文件形式的datepicker。提交表格后,我需要在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);
我尝试了上述代码,并且我获得的值不确定。
添加[(ngmodel(]
<input type="text" class="datepicker" [(ngModel)]="from" id ="from" name="from" placeholder="From:">
和.ts声明
public from;
那么,它应该在OnSubmit函数中可以避免
请参阅此stackblitz
https://stackblitz.com/edit/angular-dcr7ub
请注意以[(ngModel)]="date"
链接到app.component.ts
中的CC_1链接的两种绑定,尽管您可以使用反应性表格进行此操作。
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>
我遇到了一些棘手的事情:
- 导入获得基本示例所需的一切https://material.angular.io/components/datepicker/examples需要一些Google,然后仔细检查API TAB
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
(datepicker对此不可知(。
- 记住在
styles.css
中包括一个主题,我使用了:
@import '@angular/material/prebuilt-themes/deeppurple-amber.css';
因此,在我的示例中,日期是一刻(https://momentjs.com/(对象,因此.format()
在:
onSubmit() {
console.log((<any>this.date).format());
}