本文介绍了无法绑定到"formControl",因为它不是"input"的已知属性-Angular2材质自动完成问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Angular 2项目中使用Angular Material 自动完成组件.我在模板中添加了以下内容.

I am trying to use Angular Material Autocomplete component in my Angular 2 project. I added the following to my template.

<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指令.

I'm getting the following error. It looks like the formControl directive is not being found.

这是什么问题?

推荐答案

使用formControl时,必须将ReactiveFormsModule导入到imports数组中.

While using formControl, you have to import ReactiveFormsModule to your imports array.

示例:

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

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    MaterialModule,
  ],
  ...
})
export class AppModule {}

这篇关于无法绑定到"formControl",因为它不是"input"的已知属性-Angular2材质自动完成问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:19