錯誤描述 當form表單加FormGroup屬性時報錯 Can't bind to 'formGroup' since it isn't a known property of 'form' 原因分析與解決方案 在使用form表單時,如果用到了form-group與formControlName,需 ...
錯誤描述
當form表單加FormGroup屬性時報錯 Can't bind to 'formGroup' since it isn't a known property of 'form'
<form nz-form [formGroup]="valForm" (ngSubmit)="submit()" role="form"> <div nz-form-item> <div nz-form-control [nzValidateStatus]="valForm.controls.email"> <nz-input formControlName="email" [nzPlaceHolder]="'郵箱'" [nzSize]="'large'"> <ng-template #suffix> <i class="anticon anticon-mail"></i> </ng-template> </nz-input> <div nz-form-explain *ngIf="valForm.controls.email.dirty&&valForm.controls.email.hasError('required')">郵箱必填</div> </div> </div> <div nz-form-item> <div nz-form-control [nzValidateStatus]="valForm.controls.password"> <nz-input formControlName="password" [nzPlaceHolder]="'密碼'" [nzType]="'password'" [nzSize]="'large'"> <ng-template #suffix> <i class="anticon anticon-lock"></i> </ng-template> </nz-input> <div nz-form-explain *ngIf="valForm.controls.password.dirty&&valForm.controls.password.hasError('required')">密碼必填</div> </div> </div> <div nz-form-item nz-row> <div nz-col [nzSpan]="12"> <label nz-checkbox formControlName="remember_me"> <span>記住密碼</span> </label> </div> <div nz-col [nzSpan]="12" class="text-right"> <a [routerLink]="['/forget']">註冊</a> </div> </div> <div nz-form-item nz-row> <div nz-col [nzSpan]="24"> <button nz-button [disabled]="!valForm.valid" [nzType]="'primary'" [nzSize]="'large'" class="ant-btn__block"> <span>登錄</span> </button> </div> </div> </form>
原因分析與解決方案
在使用form表單時,如果用到了form-group與formControlName,需要在app.module.ts中的import引入的不僅僅有FormsModule,還要引入ReactiveFormsModule。如果是懶載入,則按需在各自的module中引入。如下:
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { LoginComponent } from './login/login.component'; @NgModule({ imports: [ CommonModule, FormsModule, ReactiveFormsModule ], declarations: [ LoginComponent ], providers: [ ] }) export class AccountModule { }