我正在尝试在我的 Angular 2 项目中使用 Angular Material Autocomplete组件。我将以下内容添加到我的模板中。
<md-input-container> <input mdInput placeholder="Category" [mdAutocomplete]="auto" [formControl]="stateCtrl"> </md-input-container> <md-autocomplete #auto="mdAutocomplete"> <md-option *ngFor="let state of filteredStates | async" [value]="state"> {{ state }} </md-option> </md-autocomplete>
以下是我的组件。
import {Component, OnInit} from "@angular/core"; import {ActivatedRoute, Router} from "@angular/router"; import {FormControl} from "@angular/forms"; @Component({ templateUrl: './edit_item.component.html', styleUrls: ['./edit_item.component.scss'] }) export class EditItemComponent implements OnInit { stateCtrl: FormControl; states = [....some data....]; constructor(private route: ActivatedRoute, private router: Router) { this.stateCtrl = new FormControl(); this.filteredStates = this.stateCtrl.valueChanges.startWith(null).map(name => this.filterStates(name)); } ngOnInit(): void { } filterStates(val: string) { return val ? this.states.filter((s) => new RegExp(val, 'gi').test(s)) : this.states; } }
我收到以下错误。似乎formControl找不到该指令。
formControl
无法绑定到“formControl”,因为它不是“输入”的已知属性
这里有什么问题?
使用formControl时,您必须导入ReactiveFormsModule到您的imports数组中。
ReactiveFormsModule
imports
例子:
import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ imports: [ BrowserModule, FormsModule, ReactiveFormsModule, MaterialModule, ], ... }) export class AppModule {}