angular - 角度反应形式 - 更改输入类型触发表单验证
问题描述
我有一个使用 Angular 11.2.7 和 Angular Material 制作的简单注册表单。这是堆栈闪电战。
我将密码字段的可见性更改为最后 3 秒,然后它们的状态更改回“密码”。因此,当用户在任何密码控件中单击“眼睛”时,密码文本会以明文形式显示,然后在 3 秒内变回圆点。
但是这个状态变化触发了整个表单验证的问题,并且所有无效的都得到“无效”的外观(变红)。谁能告诉我为什么?
此外,我不得不为我的 Observables 使用多播,这可能我做得不对。我不确定。
解决方案
Hi the problem is that a button without any defined type in a form acts like a submit button for the form and the required fields will show error. Just add type='button'
to button labels.
form [formGroup]="frm">
<div class="example-container">
<mat-form-field appearance="fill">
<mat-label>Email</mat-label>
<input
type="email"
matInput
placeholder="yourname@domain.com"
formControlName="email"
required
/>
<mat-error *ngIf="isTouchedAndInvalid('email')">{{ getErrorMessage("email") }}</mat-error>
</mat-form-field>
</div>
<div class="example-container">
<mat-form-field appearance="fill">
<mat-label>Enter your password</mat-label>
<input matInput [type]="(passwordType$ | async)!" />
<button
mat-icon-button
matSuffix
(click)="showPassword()"
[attr.aria-label]="'Hide password'"
type='button'
>
<mat-icon>{{ hidePassVisibility$ | async }}</mat-icon>
</button>
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Confirm password</mat-label>
<input matInput [type]="(passwordType$ | async)!" />
<button
mat-icon-button
matSuffix
(click)="showPassword()"
[attr.aria-label]="'Hide password'"
type='button'
>
<mat-icon>{{ hidePassVisibility$ | async }}</mat-icon>
</button>
</mat-form-field>
</div>
</form>