如何根据在 Angular 中选中的复选框启用/禁用按钮 [英] How to enable / disable a button based on a checkbox being checked in Angular

查看:48
本文介绍了如何根据在 Angular 中选中的复选框启用/禁用按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向我的 Angular 应用的表单添加验证.

我的表单的第一部分包含:

  • 1 个复选框
  • 2 个单选按钮组
  • 1 个按钮(导航到表单的下一部分)

按钮将被禁用,直到用户选中复选框 &从两个单选按钮组中选择一个选项.

这是我的按钮的代码:

<按钮[已禁用]="theChkAcceptTerms.invalid ||theInsuredType.invalid ||theReportInjury.invalid>

这是我的复选框的代码:

</复选框>

目前,当页面加载时,按钮被禁用.只有在我选中复选框后才启用它,&在两个无线电组中选择一个选项.

但是,如果我取消选中该复选框,则不会禁用该按钮.

如果未选中复选框,有人可以告诉我如何禁用上述按钮.非常感谢!

解决方案

您需要获取控件的双向数据绑定,并在 disabled 属性中将它们检查为

[disabled]="!checkBox || !radioGroup1 || !radioGroup2"

查看我创建的示例此处

I am trying to add validation to my Angular app's form.

The first section of my form contains:

  • 1 checkbox
  • 2 radio button group's
  • 1 button (which navigates to the next section of the form)

The button is to be disabled until the user checks the checkbox & chooses an option from both radio button group's.

Here is the code for my button:

<button
    [disabled]="
        theChkAcceptTerms.invalid || 
        theInsuredType.invalid || 
        theReportInjury.invalid
        ">

And here is the code for my checkbox:

<checkbox
    id="accept"
    heading="I accept"
    name="accept"
    value="accept"
    [(ngModel)]="chkAcceptTerms"
    required
    #theChkAcceptTerms="ngModel">
</checkbox>

Currently, when the page loads the button is disabled. It is only enabled once I check the checkbox, & choose an option in both radio groups.

However, if I un-check the checkbox, the button is not disabled.

Can someone please tell me how I can disable the above button if the checkbox is not checked. Thanks a lot!

解决方案

You need to get the two way data binding for your controls and check them in the disabled attribute as

[disabled]="!checkBox || !radioGroup1 || !radioGroup2"

Check out the sample I created HERE

这篇关于如何根据在 Angular 中选中的复选框启用/禁用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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