我在获取 checkbox
的值时遇到问题。这是片段:
<div class="list-group-item" *ngFor="let ticket of tickets">
<input
type="checkbox"
[name]="ticket.id"
[id]="ticket.id"
[value]="ticket.id"
formControlName="ticketTypes"
/>
<label for="{{ ticket.id }}">{{ ticket.name }}</label>
</div>
我正在将复选框的值设置为 true
。如何正确获取复选框值?
这是一个stackblitz
最佳答案
您可以使用 (change)
每次在输入元素上检测到更改时都会触发,然后编写自定义逻辑以从列表中获取选中的项目,例如:
HTML:
<div class="list-group-item" *ngFor="let ticket of tickets">
<input type="checkbox" [name]="ticket.id" [id]="ticket.id" [value]="ticket.id" (change)="onCheck(ticket.id)"/>
<label for="{{ ticket.id }}">{{ ticket.name }}</label>
</div>
<pre>{{tickets | json}}</pre>
TS代码:
import { Component } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
tickets = [{ id: 1, name: "Test1" }, { id: 2, name: "Test2" }];
checkedTickets = [];
onCheck(evt) {
if (!this.checkedTickets.includes(evt)) {
this.checkedTickets.push(evt);
} else {
var index = this.checkedTickets.indexOf(evt);
if (index > -1) {
this.checkedTickets.splice(index, 1);
}
}
console.log(this.checkedTickets);
}
}
关于javascript - 使用 Angular 获取复选框的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58747248/