我有一个使用 Angular 11.2.7 和 Angular Material 制作的简单注册表单。这是stackblitz。
我将密码字段的可见性更改为最后 3 秒,然后它们的状态变回“密码”。因此,当用户点击任何密码控件中的“眼睛”时,密码文本将以明文显示,然后在 3 秒后变回点。
但是这个状态改变触发了整个表单验证的问题,所有无效的都变成了“无效”的样子(变红)。谁能告诉我为什么?
此外,我不得不为我的 Observable 使用多播,但我可能做得不对。我不确定。
答案 0 :(得分:2)
嗨,问题是表单中没有任何定义类型的按钮就像表单的提交按钮一样,必填字段将显示错误。只需将 type='button'
添加到按钮标签即可。
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>