我已经看过其他几篇关于此的文章,但在使用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>
I get this error for the html code above: 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() {
}
}
I have been trying to debug this issue for several hours now and I'm not sure if this is an Angular v9 issue. I found a stackblitz example from another stackoverflow question which illustrates the expected behavior here (running Angular v7 I think): 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{ }
You need to make sure that the
FormsModule
is imported in the module that yourExampleComponent
is declared