在 angular 代码中使用 formControl

use formControl in angular code

我无法在我的垫子中使用 formControl-select。

我将从文件中删除所有不必要的数据。

这是我的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"
}

文件夹结构:

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

并在 myComponent.module

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

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

现在我的 component.html 和来自 https://material.angular.io/components/select/overview 的 ts:

 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>

我在执行时出现这个错误:

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. ("

我错过了什么?

您必须在使用 [formControl] 的模块中导入 ReactiveFormsModule:

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

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