【发布时间】:2019-06-05 17:21:30
【问题描述】:
FormControl 在指令方面遇到困难...
我正在尝试在我的输入字段中实现自动完成功能。我正在使用以下角度材料指南,我已经逐字复制并粘贴了他们的打字稿和 html 来测试它:https://material.angular.io/components/autocomplete/overview。
我在 HTML 中不断收到有关 FormControl 的错误消息:“任何适用的指令或输入元素都没有提供属性 FormControl。检查信息:报告元素上未定义的属性、事件或结构指令绑定。”
HTML CODE:
<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [FormControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
TS CODE:
import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
@Component({
selector: 'mySelector',
templateUrl: 'myTemplate.html',
styleUrls: ['myCSS.css'],
})
export class myExportClass implements OnInit {
myControl = new FormControl();
options: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable<string[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(value => this._filter(value))
);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option =>
option.toLowerCase().includes(filterValue));
}
}
【问题讨论】:
-
愚蠢的问题:您是否导入了适当的材料模块以使组件具有访问权限?您是否还重新导出了材料模块?
-
还有……你导入了 ReactiveFormsModule 了吗?
-
[FormControl]应以小写开头:[formControl] -
@MikeTung 我相信是这样
-
@jpavel 我在发布之前尝试了这两个建议,它们都不起作用:/上面的代码与 Angular Material 网站上的代码完全相同
标签: html angular typescript