在Angular 2中输入为空时禁用按钮 [英] Disable button when input is empty in Angular 2

查看:120
本文介绍了在Angular 2中输入为空时禁用按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查输入是否为空.

I want to check whether the input is empty.

  • 如果不为空,请启用提交按钮.
  • 如果为空,则禁用提交 按钮.
  • If not empty, enable the submit button.
  • If empty, disable the submit button.

我尝试了(oninput)(onchange),但是它们没有运行.

I tried (oninput) and (onchange), but they do not run.

<input type="password" [(ngModel)]="myPassword" (oninput)="checkPasswordEmpty()"/>

checkPasswordEmpty() {
    console.log("checkPasswordEmpty runs");
    if (this.myPassword) {
        // enable the button
    }
}

推荐答案

在这种情况下,我将利用表单验证器.我将在您的输入中添加必需"验证,并使用表单的全局状态来禁用/启用您的按钮.

In this case, I would leverage form validators. I would add the "required" validation on your input and use the global state of your form to disable / enable your button.

采用模板驱动的方法,无需在组件中添加任何代码,而仅在其模板中添加东西...

With the template-driven approach, there is no code to add in your component, only stuff in its template...

以下是示例:

<form #formCtrl="ngForm">
  <input ngControl="passwordCtrl" required>
  <button [disabled]="!formCtrl.form.valid">Some button</button>
</form>

这篇关于在Angular 2中输入为空时禁用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆