Angular Material Datepicker对我不起作用

时间:2017-09-12 19:35:01

标签: angular angular-material

我试图使用日期选择器。我对复选框或单选按钮没有任何问题。但是当我尝试添加日期选择器时,我总是会收到此错误:

  

错误:模板解析错误:   无法绑定到' htmlFor'因为它不是'md-datepicker-toggle'

的已知属性

在我的app.module.ts文件中:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MdButtonModule, 
    MdCheckboxModule,
    MdCardModule,
    MdRadioModule, 
    MdDatepickerModule } from '@angular/material';

import { AppComponent } from './app.component';
import { WeekControlComponent } from './week-control.component';

@NgModule({
declarations: [
  AppComponent,
  WeekControlComponent
],
imports: [
   BrowserModule, 
   FormsModule,
   MdButtonModule, 
   MdCheckboxModule, 
   MdCardModule, 
   MdRadioModule,
   MdDatepickerModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

我有一个WeekControlComponent:

HTML
<input mdInput [mdDatepicker]="picker" placeholder="Choose a date">
<md-datepicker-toggle mdSuffix [for]="picker"></md-datepicker-toggle>
<md-datepicker #picker></md-datepicker>
TS
  import { Component, OnInit } from '@angular/core';

  @Component({
    selector: 'app-week-control',
    templateUrl: './week-control.component.html',
    styleUrls: ['./week-control.component.css']
  })
  export class WeekControlComponent implements OnInit {

    constructor() { }

    ngOnInit() {
    }
  }

我直接从angular.io材质示例页面复制了示例。我不明白为什么它不起作用。有人可以帮我吗?

2 个答案:

答案 0 :(得分:4)

如果您使用的是材料版本2.0.0-beta.8,则需要进行以下更改: -

  1. 替换HTML文件中的代码

    <md-input-container>
    <input mdInput [mdDatepicker]="picker" placeholder="Choose a date">
    <button mdSuffix [mdDatepickerToggle]="picker"></button>
    </md-input-container>
    <md-datepicker #picker></md-datepicker>
    
  2. 2.在app.module中再添加一个模块,即MdNativeDateModule

    import { MdButtonModule, 
    MdCheckboxModule,
    MdCardModule,
    MdRadioModule, 
    MdDatepickerModule, 
    MdNativeDateModule   } from '@angular/material';
    
    
     imports: [
      BrowserModule, 
    FormsModule,
    MdButtonModule, 
    MdCheckboxModule, 
    MdCardModule, 
    MdRadioModule,
    MdDatepickerModule,
    MdNativeDateModule
    

    ],

答案 1 :(得分:3)

只需安装最新的角度依赖项。即。

"@angular/animations": "4.3.0",
"@angular/cdk": "^2.0.0-beta.10",
"@angular/common": "4.3.0",
"@angular/compiler": "4.3.0",
"@angular/core": "4.3.0",
"@angular/forms": "4.3.0",
"@angular/http": "4.3.0",
"@angular/material": "^2.0.0-beta.10",
"@angular/platform-browser": "4.3.0",
"@angular/platform-browser-dynamic": "4.3.0",
"@angular/platform-server": "4.3.0",
"@angular/router": "4.3.0"

devDependencies:
"@angular/compiler-cli": "4.3.0"

测试你的代码。它对我来说很好。