错误描述
当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 { }
Angular 报错 Can't bind to 'formGroup' since it isn't a known property of 'form'
时间: 2024-10-12 05:30:43