【问题标题】:FormControl is not provided by any applicable directives任何适用指令均未提供 FormControl
【发布时间】: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


【解决方案1】:

如文档中所述:"For this example, be sure to import ReactiveFormsModule from @angular/forms into your NgModule"

因此请确保您的 app.module 包含该模块,例如:

import {FormsModule, ReactiveFormsModule} from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

【讨论】:

  • 只导入ReactiveFormsModule(没有FormsModule)也对我有用,使用Angular 7
  • FormsModule 用于模板驱动表单。 ReactiveFormsModule 用于响应式表单。
猜你喜欢
  • 1970-01-01
  • 2016-07-20
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-21
  • 1970-01-01
  • 2019-04-23
相关资源
最近更新 更多