【问题标题】:Angular9-MatDatePicker: Can't bind to 'ngModel' since it isn't a known property of 'input'Angular 9-Mat DatePicker:无法绑定到“ngModel”,因为它不是“输入”的已知属性
【发布时间】:2020-05-24 19:42:56
【问题描述】:

我查看了其他几个关于此的帖子,但我仍然在使用 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{ }

【问题讨论】:

    标签: html angular typescript angular-material


    【解决方案1】:

    您需要确保将 FormsModule 导入到声明 ExampleComponent 的模块中

    【讨论】:

    • app.module.ts 和 ts 文件都导入了,请看代码块
    • 我看到了,ExampleComponent 是在 app.module.ts 中声明的,还是在另一个模块中声明的?如果它在另一个模块中声明,请尝试在那里导入它。
    • 其实……不,不是。示例组件属于主网站内的一个模块。所以有一个应用程序,它是主网站 -> 模块 1(仪表板) -> 有 ExampleComponent 作为声明。
    • 好的,然后在模块 1(仪表板)中导入 FormsModule 看看是否解决不了
    • 就是这样......我从未想过这可能是问题所在。谢谢!!!
    猜你喜欢
    • 2016-12-18
    • 2016-12-17
    • 2016-12-17
    • 1970-01-01
    • 2017-11-30
    • 2018-12-28
    • 2018-07-21
    相关资源
    最近更新 更多