gpt4 book ai didi

javascript - Angular 。为什么复选框表现得很奇怪?

转载 作者:行者123 更新时间:2023-11-30 19:03:14 24 4
gpt4 key购买 nike

这是 codesandbox 上的代码示例

还是现场看比较好。基本上发生的事情是您单击一个复选框,然后另一个复选框被勾选。我检查了它已更改的数据,它已正确显示。 [checked] 绑定(bind)应该是假的,但它是真的。

这里可能发生了一些特定于 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com