简体   繁体   English

如何根据 angular 8 中的复选框选择启用/禁用按钮

[英]How to enable/disable a button based on selection of checkbox in angular 8

I have few checkboxes which are coming from ngFor.我有几个来自 ngFor 的复选框。 I have a button which is disabled onload.我有一个在加载时禁用的按钮。 If I select/unselect only other checkboxes(which are not selected), button will be enable.如果我只选择/取消选择其他复选框(未选中),按钮将被启用。 If I unselect any selected checkbox button will be enable.如果我取消选择任何选中的复选框按钮将被启用。 If I select back again selected checkboxes button will be disable.如果我 select 再次返回选中的复选框按钮将被禁用。 Here is the code below https://stackblitz.com/edit/angular-mthf93?file=src%2Fapp%2Fapp.component.html这是下面的代码https://stackblitz.com/edit/angular-mthf93?file=src%2Fapp%2Fapp.component.html

app.component.html app.component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>
<div>
  <div *ngFor="let testitem of testVar">
    <input type="checkbox"  [checked]= "testitem.checked" (change)="changeit(testitem)" class="example-margin"/>
{{testitem.name}}
  </div>
  <button [disabled]="disabled">Submit</button>
</div>

app.component.ts app.component.ts

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

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  testVar: any;
  disabled = true;
  name = "Angular";
  ngOnInit(): void {
    this.testVar = [
      { id: 1, name: "apple", checked: false },
      { id: 2, name: "banana", checked: true },
      { id: 3, name: "orange", checked: false }
    ];
  }

  changeit(testitem) {
    console.log(testitem.checked);
    if (testitem.checked == false) {
      this.disabled = false;
    } else {
      this.disabled = true;
    }
  }
}

From the discussion following requirement was elaborated: Here main requirement is if you make any new change, button will only be enable.so that those new changes can be saved into DB by clicking the button.从讨论中详细阐述了以下要求:这里的主要要求是,如果您进行任何新更改,则仅启用按钮。以便可以通过单击按钮将这些新更改保存到数据库中。

Possible solution: You have to get the initial state and the current state somehow.可能的解决方案:您必须以某种方式获得初始 state 和当前 state。 Probably you should use a formGroup and split the current form from the model and diff it with that.可能您应该使用 formGroup 并将当前表单从 model 中拆分出来并与之进行比较。 I Just hacked the requirement it into https://stackblitz.com/edit/angular-eysswr?file=src/app/app.component.ts - but in my opinion should you split your model from the form for this requirement.我刚刚将要求修改为https://stackblitz.com/edit/angular-eysswr?file=src/app/app.component.ts - 但在我看来,您是否应该将 model 与此要求的表格分开。 see

just checking the current element will never allow you to check if the button must be disabled.仅检查当前元素将永远不允许您检查按钮是否必须被禁用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM