544

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>

Following is my component.

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;
    }
}

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

Can't bind to 'formControl' since it isn't a known property of 'input'

What is the issue here?

MathMax
  • 571
  • 7
  • 22
Lahiru Chandima
  • 22,324
  • 22
  • 103
  • 179
  • 12
    one comment to Pengyy's answer: While using `formControl`, you have to import `ReactiveFormsModule` to your **module**, not *rootModule*. Just in case you use `FormControl` in your feature modules. – King John Jul 15 '17 at 14:06
  • 1
    I have similar case and have the import for ReactiveFormsModule in my feature. The only difference is that I would like to bind to 'formControlName' instead of 'formControl'. The message has the same structure – Искрен Станиславов Sep 14 '17 at 14:51
  • 1
    The answers here are correct; but if anyone is still stuck (like I was) and the error says `formcontrol` (lowercase) rather than `formControl` — if you're running templates through webpack html-loader, this will help: https://stackoverflow.com/a/40626329/287568 – Ben Boyle Jan 15 '19 at 02:43

11 Answers11

1103

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

Example:

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

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    MaterialModule,
  ],
  ...
})
export class AppModule {}
Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Pengyy
  • 37,383
  • 15
  • 83
  • 73
  • 245
    Really, why isn't this in the doc at https://material.angular.io/components/autocomplete/overview so much time wasted for this. Magical unknown dependencies everywhere with angular. – Vadorequest Sep 26 '17 at 22:03
  • 9
    @Vadorequest: Those docs are for Material. If they start adding docs for every feature of Angular that they use, there could end up being lots of duplication between the Angular docs and the Material docs that will eventually slip out of sync. But I spent a good amount of time scratching my head at this too. You could always submit an issue to the material github repo: https://github.com/angular/material2/issues – Eric Ihli Sep 28 '17 at 15:29
  • 37
    That's no excuse IMHO. They could do something about, maybe a "general troubleshootings" that links to some kind of tips. If their library depends on other native angular dependencies, it's also their task to highlight those deps. Especially in this case, their framework is on "material.angular.io" after all. – Vadorequest Sep 30 '17 at 07:59
  • 4
    Or just a standard tooling that automatically pulls in these types of modules based on what you're using. Sounds like a job for webpack? – ferr Oct 29 '17 at 22:37
  • 1
    The need to use ReactiveFormsModule is clear if you look within Stackblitz in the autocomplete docs. More generally, any component will have more details in its Stackblitz demo than the in-page code... – David Haddad Feb 28 '19 at 09:37
  • I am happy to announce this solution is covered by Assistant https://medium.com/@tomaszs2/mapping-stackoverflow-into-real-time-assistance-e627dda88f69 – Tom Smykowski Jul 26 '20 at 08:55
  • I was getting the same error "Can't bind to 'formControl' since it isn't a known property of 'input'.", and got it resolved by importing ReactiveFormsModule, in the app module. Thank you. – Rajkumar M Dec 03 '20 at 18:08
  • Also, include the component in the declarations array. – Edward Olamisan Nov 30 '22 at 01:11
67

Forget trying to decipher the example .ts - as others have said it is often incomplete.

Instead just click on the 'pop-out' icon circled here and you'll get a fully working StackBlitz example.

enter image description here

You can quickly confirm the required modules:

enter image description here

Comment out any instances of ReactiveFormsModule, and sure enough you'll get the error:

Template parse errors:
Can't bind to 'formControl' since it isn't a known property of 'input'. 
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • 1
    Is there a reason the documentation is missing this and we need to hunt through the StackBlitz to see what they omitted?? – SpaceNinja Mar 16 '22 at 17:59
  • 1
    @SpaceNinja just a cut and paste issue I guess but yes they really ought to have fixed it by now - I get the upvotes so I have ulterior motives not to report it lol. – Simon_Weaver Jun 14 '22 at 02:17
32

Another reason this can happen:

The component you are using formControl in is not declared in a module that imports the ReactiveFormsModule.

So check the module that declares the component that throws this error.

Yuri
  • 4,254
  • 1
  • 29
  • 46
Kshitij Banerjee
  • 1,678
  • 1
  • 19
  • 35
5

From version 9.1.4 you only need to import ReactiveFormsModule

https://angular.io/guide/reactive-forms

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
Dev Better
  • 51
  • 1
  • 2
3

if your are using standalone components the import of ReactiveFormsModule has to be inside the own component instead of 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

In angular 12 the imports path for matautocompleteModule is changed and it solved my problem.... Now it look like this enter image description here

Zia Khan
  • 188
  • 2
  • 9
2

What worked for me was moving my imports to be before my declaration and export, no idea why this worked but it did...

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    MatSlideToggleModule,
  ],
  declarations: [SettingsComponent],
  exports: [
    SettingsComponent
  ]
})
export class SettingsModule { }

DJIM
  • 21
  • 4
1

Well what worked for me was to build the form within the template `` in the @component({}), for example--


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 {
  }

}

This stopped showing errors. If the error persists then this could work out for you

Whizfactor
  • 41
  • 1
  • 1
  • 4
1

I had just added the FormsModule to the imports of AppModule, but it did not work Had to add the ReactiveFormsModule as well

0

Start by adding a regular matInput to your template. Let's assume you're using the formControl directive from ReactiveFormsModule to track the value of the input.

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values, and implement more advanced forms.

import { FormsModule, ReactiveFormsModule } from "@angular/forms"; //this to use ngModule

...

imports: [
    BrowserModule,
    AppRoutingModule,
    HttpModule,
    FormsModule,
    RouterModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    MaterialModule],
0

for me the error was i was doing [FormControl] so instead of capital F use [formControl]