无法将'formControl'绑定到'input',因为它不是'input'的已知属性 - Angular2 Material自动完成问题

553

我正在尝试在我的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'绑定到'input',因为它不是'input'的已知属性

这里出现了什么问题?


13
给Pengyy答案的一个评论:在使用formControl时,你需要将ReactiveFormsModule导入到你的模块中,而不是根模块。以防你在功能模块中使用FormControl - King John
1
我有类似的情况,并且在我的功能中导入了ReactiveFormsModule。唯一的区别是我想要绑定到'formControlName'而不是'formControl'。消息具有相同的结构。 - Искрен Станиславов
1
这里的答案是正确的;但如果有人仍然卡住了(就像我一样),并且错误提示说 formcontrol(小写)而不是 formControl — 如果你正在通过 webpack html-loader 运行模板,这将会有所帮助:https://dev59.com/Hpzha4cB1Zd3GeqPGYj0#40626329 - Ben Boyle
11个回答

1112

使用 formControl 时,你需要将 ReactiveFormsModule 导入到你的 imports 数组中。

示例:

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

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

246
真的,为什么 https://material.angular.io/components/autocomplete/overview 上面没有这个文档,这浪费了我们太多时间。Angular 中到处都是神秘的未知依赖。 - Vadorequest
9
那些文档是关于Material的。如果他们开始为使用的Angular的每个功能添加文档,Angular文档和Material文档之间可能会出现大量重复,并最终不同步。但我也花了很多时间来琢磨这个问题。您可以随时向材料github库提交问题:https://github.com/angular/material2/issues - Eric Ihli
37
在我看来,这并不是借口。他们可以采取一些措施,例如提供指向某些提示的“常规故障排除”链接。如果他们的库依赖于其他本地的Angular依赖项,那么突出显示这些依赖项也是他们的任务。特别是在这种情况下,毕竟他们的框架是在“material.angular.io”上的。 - Vadorequest
4
听起来像是 webpack 的工作,自动拉取这些类型的模块并根据你使用的内容进行处理,或者只是一个标准的工具集? - ferr
1
如果您在自动完成文档中查看Stackblitz,就会清楚地了解使用ReactiveFormsModule的必要性。更一般地说,任何组件在其Stackblitz演示中都将比页面代码具有更多细节... - David Haddad
显示剩余3条评论

67

忘记尝试解密示例 .ts - 正如其他人所说,它经常是不完整的。

相反,只需点击这里标出的 “弹出” 图标,您将获得一个完全工作的 StackBlitz 示例

在此输入图像描述

您可以快速确认所需的模块:

在此输入图像描述

注释掉任何ReactiveFormsModule的实例,确定您将会得到错误:

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

1
文档中缺少这个内容的原因是什么?我们需要在 StackBlitz 中寻找他们遗漏了什么吗? - SpaceNinja
1
@SpaceNinja 可能只是一个复制粘贴问题,但是他们真的应该早点解决 - 我得到了赞,所以我有别的动机不报告它哈哈。 - Simon_Weaver

32

造成这种情况的另一个原因是:

你正在使用的组件中,formControl 未在导入 ReactiveFormsModule 的模块中进行声明。

因此,请检查抛出此错误的组件所在的模块。


谢谢两次。我不能点赞两次,所以我决定在这里写下来。 - Fakt309

5

我在 Angular 11 版本中尝试了这个方法,它也起作用了,谢谢。 - Bruno Giubilei

4

如果您正在使用独立组件,则ReactiveFormsModule的导入必须在自己的组件中而不是app.module.ts中进行。

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

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css'],
  standalone: true,
  imports: [ ReactiveFormsModule ]
})
export class FormRecipesComponent {

constructor() {}

name = new FormControl('');

}

2
我的解决方法是将导入语句放在声明和导出之前,不知道为什么这样做就可以了...
@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    MatSlideToggleModule,
  ],
  declarations: [SettingsComponent],
  exports: [
    SettingsComponent
  ]
})
export class SettingsModule { }


2
在 Angular 12 中,matAutocompleteModule 的导入路径已更改,这解决了我的问题...现在它看起来像这样: enter image description here

2
我刚刚在AppModule的导入中添加了FormsModule,但它没有起作用 不得不再添加ReactiveFormsModule

1

对我来说有效的方法是在模板``中构建表单,例如在@component({})中--


import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-contact-form',
  template:`
  <form class="validation-form" validate method="createUserWithEmailAndPassword">
  <div class="form-row">
    <div class="col-md-6 mb-3">
      <label for="firstName">First name</label>
      <input type="text" [formControl]="firstName" id="firstName" placeholder="Please enter your first name" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
    <div class="col-md-6 mb-3">
      <label for="lastName">Last name</label>
      <input type="text" [formControl]="lastName" id="lastName" placeholder="Please enter your last name" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
  </div>
    <div class="form-row">
      <div class="col-md-6 mb-3">
        <label for="email">Email address</label>
        <input type="email" [formControl]="email" id="email" aria-describedby="emailHelp" placeholder="Please enter your last name" required>
        <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
        <div class="valid-feedback">
          Looks good!
        </div>
      </div>
    </div>
    <div class="col-md-6 mb-3">
      <label for="password">Password</label>
      <input type="password" [formControl]="password" id="password" placeholder="Please enter your password" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <label for="zip">Zip</label>
      <input type="text" [formControl]="zip" id="zip" required>
      <div class="invalid-feedback">
        Please provide a valid zip.
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
      <label class="form-check-label" for="invalidCheck">
        Agree to terms and conditions
      </label>
      <div class="invalid-feedback">
        You must agree before submitting.
      </div>
    </div>
  </div>
  <button class="btn btn-primary" type="submit">Submit form</button>
</form>`,

  templateUrl: './contact-form.component.html',
  styleUrls: ['./contact-form.component.scss']
})
export class ContactFormComponent implements OnInit {

  firstName =  new FormControl('');
  lastName =  new FormControl('');
  email =  new FormControl('');
  password =  new FormControl('');

  constructor() { }

  ngOnInit(): void {
  }

}

这个停止显示错误了。如果错误仍然存在,那么这可能适合您。


0

对我来说,错误是我使用了 [FormControl],所以应该使用小写的 [formControl]


1
这显然不适用于楼主。 - Random

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接