【发布时间】:2017-08-30 10:16:23
【问题描述】:
我正在尝试在我的 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”,因为它不是“输入”的已知属性
这里有什么问题?
【问题讨论】:
-
对 Pengyy 回答的评论:在使用
formControl时,您必须将ReactiveFormsModule导入到您的 模块,而不是 rootModule。以防万一您在功能模块中使用FormControl。 -
我有类似的情况,并且在我的功能中导入了 ReactiveFormsModule。唯一的区别是我想绑定到“formControlName”而不是“formControl”。消息具有相同的结构
-
这里的答案是正确的;但是如果有人仍然卡住(就像我一样)并且错误显示
formcontrol(小写)而不是formControl- 如果您通过webpack html-loader运行模板,这将有所帮助:stackoverflow.com/a/40626329/287568
标签: angular typescript angular-material2 angular-forms