以下是 codesandbox 上此代码的示例
最好还是现场观看。基本上发生的情况是,您单击一个复选框,然后另一个复选框被勾选。我检查了更改后的数据,它显示正确。 [checked] 绑定(bind)应该是 false,但它是 true。
这里可能发生了特定于 Angular 事情,我看不出我做错了什么,但显然有些事情。
在此处复制代码:
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<div *ngFor="let value of getDays(); let i = index">
<input
type="checkbox"
[checked]="value === 1"
(change)="setDay($event, i + 1)"
[id]="'day' + i"
/>
<label [for]="'day' + i">
day {{i + 1}}
</label>
</div>
</div>
和app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title = "CodeSandbox";
days = {
day_1: 0,
day_2: 0,
day_3: 0,
day_4: 0,
day_5: 0,
day_6: 0,
day_7: 0
};
getDays() {
return Object.values(this.days);
}
setDay(event, index) {
const newDays = { ...this.days };
newDays["day_" + index] = Number(event.target.checked);
this.days = newDays;
console.log(this.days, "days");
}
}
最佳答案
您可以创建变量并存储对象的值:
typescript :
daysArray = Object.values(this.days);
HTML:
<div *ngFor="let value of daysArray; let i = index">
<input
type="checkbox"
[checked]="value===1"
(change)="setDay($event, i + 1)"
[id]="'day' + i"
/>
<label [for]="'day' + i">
day {{i + 1}}
</label>
<p>value is {{ value }}</p>
</div>
关于javascript - 有 Angular 。为什么复选框表现得很奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59274382/