【发布时间】:2020-11-11 15:40:12
【问题描述】:
所以我注意到很多关于此的线程,但都是较旧的并且没有官方解决方案。
也许现在有解决这个问题的办法。
但基本上,如果您有一个带有用户名输入字段的表单,当页面第一次加载时,如果浏览器自动填充该值(因为您将凭据保存在浏览器中),“login”按钮仍将被禁用,因为在用户第一次点击任意位置之前,表单仍然无效。
我发现的最新提议的解决方案是使用 Angular 官方:AutofillMonitor
但它不起作用:
@ViewChild("email") inputEl: ElementRef;
constructor(
private formBuilder: FormBuilder,
private _autofill: AutofillMonitor
){
this.emailForm = this.formBuilder.group(
{
userLogin: [
"",
{
validators: [Validators.required],
},
],
password: [
"",
{}
]
}
);
}
ngAfterViewInit() {
this._autofill.monitor(this.inputEl)
.subscribe(e => {
if (e.isAutofilled) {
// this works, the code gets in here onInit
this.forceValidityCheck();
}
}
);
}
forceValidityCheck() {
this.emailForm.controls["userLogin"].updateValueAndValidity();
}
HTML 代码:
<ng-container>
<form [formGroup]="emailForm" (ngSubmit)="checkAndLoadUserInfo(emailForm.get('userLogin').value)">
<mat-form-field appearance="standard" class="standardInputField">
<mat-label translate>enter_email.username</mat-label>
<input matInput formControlName="userLogin" #email type="email" placeholder="name@example.org" (keyup.enter)="checkAndLoadUserInfo(emailForm.get('userLogin').value)" autofocus autocomplete="username">
<label class="pswValidationLabels" *ngIf="emailForm.get('userLogin').hasError('doesNotExist')" translate>
enter_email.unknown_user
</label>
</mat-form-field>
<mat-form-field appearance="standard" class="hiddenFormField">
<input matInput type="password" autocomplete="current-password">
</mat-form-field>
<div>
<button [disabled]="!emailForm.get('userLogin').valid" mat-raised-button>
</button>
</div>
</form>
</ng-container>
但是即使这样,表单仍然无效,直到用户点击屏幕上的任意位置,它才会生效。
这个有官方解决方案吗?
【问题讨论】:
-
也分享
html代码 -
如果你在
forceValidityCheck之后打印this.emailForm.valid,它会说什么? -
@SRana 添加了 html 代码
-
@MarcellKiss“无效”
-
试试这个
[disabled]="emailForm.invalid && emailForm.touched"