首页 文章

Angular2表单禁用提交

提问于
浏览
4

我用一个带有angular2的注册表格进行了recaptcha . 我有一个控制器来匹配recaptcha与所需的验证器 .

this.captchaControl = fb.control(false, Validators.required); 
this.userForm = fb.group({
    ...
    captchaControl: this.captchaControl
});

当用户回答它时,该值正确设置为true .

checkReCaptcha(response){
    console.log(this.userForm.valid);
    this.captcha = response;
    this.captchaControl.updateValue(true);
    console.log(this.userForm.valid);
}

第一个控制台日志显示为false,第二个打印为true .

在提交按钮中,我放了禁用功能:

<button type="submit" [disabled]="!userForm.valid" class="btn btn-d">Register</button>

但按钮保持禁用状态 .

如何触发按钮再次检查 userForm 的有效性?

Update 这是我的问题的一个例子 . http://plnkr.co/edit/Rwy6Oc5JEEm7yIJYnxJX?p=preview

完成表单后,即使表单有效,红色按钮也会保持禁用状态 . 如果您触摸任何其他输入表单(或其他提交按钮),则禁用按钮会更新并可用,但我希望在定义所有输入后它可用...

1 回答

  • 4

    看起来像是在Angulars区域外运行的代码导致的更改检测问题 .

    注入 ApplicationRef 并在值更改后调用tick()`

    import {ApplicationRef} from 'angular2/core';
    
    constructor(private appRef:ApplicationRef){} 
    
    checkReCaptcha(response){
        console.log(this.userForm.valid);
        this.captcha = response;
        this.captchaControl.updateValue(true);
        this.appRef.tick();
        console.log(this.userForm.valid);
    }
    

    这使得Angular意识到需要进行变更检测 .

    http://plnkr.co/edit/nYKqtXaaDl69eeL35GTL?p=info

    有趣的是,没有其他方式调用变更检测实际上有效 .

    • setTimeout(...)

    • ChangeDetectorRef.markForCheck()

    • zone.run(...)

    没有导致新的更改检测运行 . 至少当我将绑定 {{userForm.valid}} 更改为 {{isUserFormValid()}} 时,未调用 isUserFormValid() .

    只有 this.appRef.tick() 使Angular2重新评估绑定 .

相关问题