我有几个来自 ngFor 的复选框。我有一个在加载时被禁用的按钮。 如果我只选择/取消选择其他复选框(未选中),按钮将被启用。 如果我取消选择任何选定的复选框按钮将被启用。 如果我再次选择返回选定的复选框按钮将被禁用。这是下面的代码 https://stackblitz.com/edit/angular-mthf93?file=src%2Fapp%2Fapp.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>
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;
}
}
}
答案 0 :(得分:0)
从讨论中阐述了以下要求: 这里的主要要求是,如果您进行任何新更改,则仅启用按钮。这样可以通过单击按钮将这些新更改保存到数据库中。
可能的解决方案: 您必须以某种方式获得初始状态和当前状态。可能你应该使用一个 formGroup 并将当前表单从模型中分离出来,然后用它来区分。我刚刚将需求修改为 https://stackblitz.com/edit/angular-eysswr?file=src/app/app.component.ts - 但在我看来,您是否应该将模型与此需求的表单分开。见
仅仅检查当前元素永远不会让你检查按钮是否必须被禁用。