Angular添加mat-error后mat-form-field不可见但可输入的问题求助
Hey there! Let's figure out why your mat-form-fields are acting up (invisible but still clickable) and fix them step by step.
Key Issues Causing the Problem
Full HTML document structure in component template
Yourapp.component.htmlincludes complete<html>,<head>, and<body>tags. Angular component templates are meant to be embedded into the root app's existing HTML document—duplicating these top-level tags causes DOM structure conflicts, which directly breaks Material component rendering (hence the invisible form fields).Mismatched form controls
Inapp.component.ts, yourFormGroupdefinesnameandlastNamecontrols, but your template usesemailandpasswordasformControlNamevalues. This mismatch throws off the form's state and disrupts Material's component logic.Unnecessary multiple
<form>tags
You’ve split your two fields into separate<form>elements, both bound to the sameformgroup. This is logically incorrect (related fields belong in one form) and can cause additional styling/interactive glitches.
Fixed Code Examples
app.component.html
<!-- website title --> <h1 class="title"> Welcome to my Website </h1> <form [formGroup]="form"> <mat-form-field class="emailFormField"> <mat-label>Email</mat-label> <input matInput formControlName="email" type="email" name="email"> <mat-error *ngIf="form.controls['email'].hasError('required')"> It is required field </mat-error> </mat-form-field> <mat-form-field class="passwordFormField"> <mat-label>Password</mat-label> <input matInput formControlName="password" type="password" name="password"> <mat-error *ngIf="form.controls['password'].hasError('required')"> It is required field </mat-error> </mat-form-field> </form>
app.component.ts
import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'yoozProject'; form: FormGroup; constructor (private fb: FormBuilder) { // Match form controls to the template's formControlName values this.form = this.fb.group({ email: ['', [Validators.required]], password: ['', [Validators.required]] }); } }
Extra Optimization Tip
To clean up your template code, add getters for your form controls in app.component.ts:
get email() { return this.form.get('email'); } get password() { return this.form.get('password'); }
Then you can simplify the error checks in the template to:
<mat-error *ngIf="email.hasError('required')">It is required field</mat-error>
内容的提问来源于stack exchange,提问作者רועי אטיאס

