Angular 2 - 表单在浏览器自动填充时无效

Pas*_*uby 21 angular2-forms angular

我有一个登录表单,其中包含电子邮件和密码字段.

我选择了浏览器自动填充功能.

问题是:当浏览器自动填充登录表单时,这两个字段都是原始且未触及的,因此禁用了提交按钮.

如果我单击禁用按钮,它会启用并触发提交操作,这很好.但是默认的禁用方面非常糟糕,可能会让一些用户感到失望.

你有一些关于如何处理的想法吗?

小智 5

我还通过检查在显示错误消息时是否触摸了表单来解决它。所以,例如,提交按钮看起来像这样

<input type="submit" class="btn btn-default" [disabled]="loginFormGroup.invalid && loginFormGroup.touched" />
Run Code Online (Sandbox Code Playgroud)

  • 因此,使用此解决方案加载页面时,如果字段为空,按钮仍将被激活 (2认同)

小智 -3

也有同样的问题。我不确定这是否是最好的方法,但我可以通过添加 AfterViewChecked 让它工作

import { Component, AfterViewChecked } from "@angular/core";

export class LoginComponent implements AfterViewChecked {
    // Beware! Called frequently!
    // Called in every change detection cycle anywhere on the page
    ngAfterViewChecked() {
        console.log(`AfterViewChecked`);
        if (this.usr.userName) {
            // enable to button here.
            console.log("found username in AfterViewChecked");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者你也许可以尝试 Angular2 的其他 Lifecycle Hooks https://embed.plnkr.co/?show=preview