我已经查看了关于此的其他几个帖子,但我仍然在使用 matdatepicker 实现 ngmodel 绑定时遇到问题。
我的 HTML:
<mat-form-field>
<mat-label>Start Date</mat-label>
<input matInput [(ngModel)]="searchStartDate" [min]="minDate" [max]="maxDate" [matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker">
</mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
对于上面的 html 代码,我收到此错误:Can't bind to 'ngModel' since it isn't a known property of 'input'.
与上述 html 代码关联的 TS 文件:
import { Component, OnInit } from '@angular/core';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
// I threw this in just in case^^
@Component({
selector: 'app-dash-home',
templateUrl: './example.component.html',
styleUrls: ['./example.component.scss']
})
export class ExampleComponent implements OnInit {
searchStartDate: Date; searchEndDate: Date
constructor() {
const todaysDate = new Date();
this.minDate = new Date(todaysDate.getFullYear() - 5, 0, 1);
this.maxDate = new Date(todaysDate.getFullYear(), todaysDate.getMonth(), todaysDate.getDate());
}
ngOnInit() {
}
}
我已经尝试调试这个问题几个小时了,我不确定这是否是 Angular v9 问题。我从另一个 stackoverflow 问题中找到了一个 stackblitz 示例,它说明了这里的预期行为(我认为运行 Angular v7):https ://stackblitz.com/edit/angular-y8hqyn-52t76k?file=app%2Fdatepicker-value-example.html
请注意 stackblitz 示例如何初始化为今天的日期?这就是我试图模仿的行为。我还在下面包含了我的 app.module.ts 以防万一。
文件:app.module.ts
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
imports: [...
FormsModule,
...]
感谢所有预期的帮助和支持
编辑:
添加 ExampleComponent 所属的模块文件:
examplecomponent.module.ts:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MaterialModule } from '../../assets/material';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [...],
imports: [
...,
FormsModule
]
})
export class ExampleComponentModule{ }