0
votes

I have few checkboxes which are coming from 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. Here is the code below https://stackblitz.com/edit/angular-mthf93?file=src%2Fapp%2Fapp.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

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;
    }
  }
}
1
But what's the question?Jeremy Thille

1 Answers

0
votes

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. Probably you should use a formGroup and split the current form from the model and diff it with that. 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. see

just checking the current element will never allow you to check if the button must be disabled.