首页 文章

't bind to ' formControl ' since it isn' t 'input'的已知属性 - angular2 material自动完成问题

提问于
浏览
170

我想在angular2项目中使用角度材料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',因为它不是'input'的已知属性

这是什么问题?

2 回答

  • 13

    忘记试图破译示例.ts - 正如其他人所说的那样,往往是不完整的 .

    enter image description here

    而只需单击此处圈出的'pop-out'图标,您将获得fully working example .

    当然,你可以看到这确实包括额外需要的模块(否则它将无法工作) .

    enter image description here

    只是为了好玩,我注释掉了 ReactiveFormsModule 的任何实例,并且确定弹出了这个错误:

    Template parse errors:
    Can't bind to 'formControl' since it isn't a known property of 'input'.
    
  • 376

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

    例:

    import {FormsModule, ReactiveFormsModule} from '@angular/forms';
    
    @NgModule({
      imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        MaterialModule,
      ],
      ...
    })
    export class AppModule {}
    

相关问题