Search code examples
angularangular5angular4-formsangular-forms

use formControl in angular code


I'm not able to use formControl in my mat-select.

I'll remove all innecessary data from files.

this is my package.json

"dependencies": {
  "@angular/cdk": "5.0.4",
  "@angular/common": "~5.2.0",
  "@angular/compiler": "~5.2.0",
  "@angular/core": "~5.2.0",
  "@angular/flex-layout": "2.0.0-beta.12",
  "@angular/forms": "~5.2.0",
  "@angular/material": "5.0.4"
}

The folder structure:

-src
  -app
    -myComponent
      -myComponent.component.html
      -myComponent.component.ts
      -myCompnent.module.ts
    -shared
      -material
         -material.module.ts
      -shared.module.ts

material.module.ts:

import { FormsModule } from '@angular/forms';
import { MatSelectModule } from '@angular/material';


@NgModule({
 providers: [],
 imports: [
    FormsModule
 ],
 exports: [
   MatSelectModule
 ]
})
 export class CustomMaterialModule {
}

shared.module.ts

import { CustomMaterialModule } from './material/material.module';

@NgModule({
  exports: [
    CustomMaterialModule
  ],
  declarations: []
})

export class SharedModule {
}

and in myComponent.module

import { SharedModule } from "../shared/shared.module";

@NgModule({
  imports: [
    SharedModule,
  ],
  declarations: [myComponent],
  exports: [myComponent]
 })
export class myComponentModule { }

Now my component.html and ts from https://material.angular.io/components/select/overview:

 export class myComponent {
 toppings = new FormControl();

 toppingList = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];


<mat-form-field>
   <mat-select placeholder="Toppings" [formControl]="toppings" multiple>
     <mat-select-trigger>
          {{toppings.value ? toppings.value[0] : ''}}
          <span *ngIf="toppings.value?.length > 1" class="example-additional-selection">
            (+{{toppings.value.length - 1}} others)
          </span>
      </mat-select-trigger>
     <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
      </mat-select>
 </mat-form-field>

I have this error when executing:

Can't bind to 'formControl' since it isn't a known property of 'mat-select'.
1. If 'mat-select' is an Angular component and it has 'formControl' input, then verify that it is part of this module.
2. If 'mat-select' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

What are I'm missing?


Solution

  • You have to import ReactiveFormsModule in the module where you use the [formControl]:

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