input添加formControl属性时报错
login.component.html:
<form class="example-form"> <mat-form-field class="example-full-width"> <mat-label>用户名</mat-label> <input matInput placeholder="请输入用户名" [formControl]="nameFormControl" [errorStateMatcher]="matcher"> <mat-error *ngIf="nameFormControl.hasError('required')"> 请输入用户名 </mat-error> </mat-form-field> <mat-form-field class="example-full-width"> <mat-label>密码</mat-label> <input matInput type="password" placeholder="请输入密码" [formControl]="passwordFormControl" [errorStateMatcher]="matcher"> <mat-error *ngIf="passwordFormControl.hasError('required')"> 请输入密码 </mat-error> </mat-form-field> </form>
login.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroupDirective, NgForm, Validators } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
export class LoginErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
}
}
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent{
nameFormControl = new FormControl('', [
Validators.required
]);
passwordFormControl = new FormControl('', [
Validators.required
]);
matcher = new LoginErrorStateMatcher();
}
在使用form表单时,如果用到了form-group与formControlName,需要在app.module.ts中的import引入的不仅仅有FormsModule,还要引入ReactiveFormsModule
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import { MatInputModule } from '@angular/material/input';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { IndexComponent } from './component/index/index.component';
import { LoginComponent } from './component/login/login.component';
import { TestComponent } from './component/test/test.component';
@NgModule({
declarations: [
AppComponent,
IndexComponent,
LoginComponent,
TestComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatInputModule,
ReactiveFormsModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
