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