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



我有几个来自ngFor的复选框。我有一个在加载时被禁用的按钮。若我只选择/取消选择其他复选框(并没有被选中(,按钮将被启用。如果我取消选择任何选中的复选框按钮将被启用。如果我再次选择返回选中的复选框按钮将被禁用。这是下面的代码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;
}
}
}

通过讨论,详细阐述了以下要求:这里的主要要求是,如果您进行任何新的更改,按钮将只被启用。因此,这些新的更改可以通过单击按钮保存到DB中。

可能的解决方案:你必须以某种方式获得初始状态和当前状态。也许你应该使用一个formGroup,将当前表单从模型中分离出来,并与之进行比较。我刚把它的要求破解了https://stackblitz.com/edit/angular-eysswr?file=src/app/app.component.ts-但在我看来,你应该把你的模型从这个要求的表格中分离出来吗。参见

只检查当前元素将永远无法检查按钮是否必须禁用。

最新更新