【问题标题】:Disable button unless checkbox is checked (Angular 7+)?除非选中复选框,否则禁用按钮(Angular 7+)?
【发布时间】:2020-04-11 10:09:22
【问题描述】:

除非选中所有复选框,否则我想禁用按钮?你如何在 Angular 中实现这一点?

这是不同的,因为它不是一个表单,而且这个问题没有得到回答,因为没有 for 循环。

    <div class="md-input-group md-checkbox md-input--nested-1">
      <input type="checkbox" class="md-input md-checkbox__input" id="checkboxNested1" name="checkboxNested1">
      <label style="margin-left: -30px;" class="md-checkbox__label" for="checkboxNested1">
        <p>Checkbox 1</p>
      </label>
    </div>

    <div class="md-input-group md-checkbox md-input--nested-1">
      <input type="checkbox" class="md-input md-checkbox__input" id="checkboxNested1" name="checkboxNested1">
      <label style="margin-left: -30px;" class="md-checkbox__label" for="checkboxNested1">
        <p>Checkbox 2</p>
      </label>
    </div>

   <button class="md-button" md-button color="red" aria-label="delete">Delete organization</button>


【问题讨论】:

  • 这能回答你的问题吗? Angular2, disable button if no checkbox selected
  • 我会给你一些提示。这些都可以在文档中找到。 [disabled] 将控制按钮是否被禁用,您可以使用表单控件对复选框进行验证。 angular.io/guide/form-validation
  • 但它不是表格
  • Angular2 没有回答我的问题,因为他有多个复选框。我只想为 2 个不同的输入做这件事
  • 这是不同的问题。

标签: html css angular typescript


【解决方案1】:

例如:Angular 2 Checkbox Two Way Data Binding

export class FooComponenet {
   checkbox1 = false; // bind first checkbox
   checkbox2 = false; // another checkbox
}
<!-- or use (change)="methodName()" -->
<input type="checkbox" [checked]="checkbox1" (change)="checkbox1 = !checkbox1"/>
<input type="checkbox" [checked]="checkbox2" (change)="checkbox2 = !checkbox2"/>

<button [disabled]="!checkbox1 || !checkbox2">Bar</button>

<!-- or this -->
<button [attr.disabled]="!checkbox1 || !checkbox2">Bar</button>

你也可以使用:

【讨论】:

  • 所以我希望在选中两个框后启用它,这会在您单击检查时禁用该按钮。
  • 你是对的。我纠正了。 :) Bool 逻辑是相反的。
【解决方案2】:

在选中复选框之前禁用表单按钮,使用 required 属性告诉 DOM 该字段是必需的,并使用 disabled 属性禁用按钮。 下面是例子

 <form #myform="ngForm">
     <div class="md-input-group md-checkbox md-input--nested-1">
        <input type="checkbox" class="md-input md-checkbox__input" id="checkboxNested1" name="checkboxNested1" **required**>
          <label style="margin-left: -30px;" class="md-checkbox__label" for="checkboxNested1">
            <p>Checkbox 1</p>
          </label>
        </div>
      <div class="md-input-group md-checkbox md-input--nested-1">
      <input type="checkbox" class="md-input md-checkbox__input" id="checkboxNested1" name="checkboxNested1" required>
      <label style="margin-left: -30px;" class="md-checkbox__label" for="checkboxNested1" >
        <p>Checkbox 2</p>
      </label>
    </div>
     <button class="md-button" md-button color="red" aria-label="delete" [disabled]="!myform.valid">Delete organization</button>

    </form>

【讨论】:

    猜你喜欢
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 2013-04-15
    • 1970-01-01
    相关资源
    最近更新 更多