我问过类似的问题。但我的问题有点不同。在表格列中,我有 Slide-Toggle 元素,用户可以无限次地使其为真或为假。之后有一个按钮,用户可以提交所有这些真值、假值。在我的 HTML 中,这些 Slide-Toggle 元素来自 for 循环,该循环是从通知数组生成的。获取所有这些滑动开关及其 ID 的值(真、假)的最简单、最好的方法是什么?正如我提到的,我将提交它们,这就是我想要这样做的原因。这是我在下面尝试的内容
HTML
<h3>Notifications</h3>
<table class="table" id="thetable">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Tasks</th>
<th scope="col">IsFinished</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let not of notifications;"
[ngStyle]="{ 'background-color': (not.isFinished ? '#dddddd' : 'white') }"
>
<th scope="row">{{not.id+1}}</th>
<td>{{not.task}}</td>
<td>
<section class="example-section">
<mat-slide-toggle
[id]="not.id"
class="example-margin"
[color]="color"
[checked]="not.isFinished"
[disabled]="not.isFinished"
(change)="onChange($event)"
>
</mat-slide-toggle>
</section>
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col">
<button mat-raised-button color="primary" (click)="openDialog()">Add Task</button>
<button mat-raised-button color="primary" (click)="onSave()">Save</button>
</div>
TypeScirpt(数组是如何出现的)
ngOnInit() {
this.notifications=this.notificationService.getNotifications();
}
最佳答案
使用 ngModel
绑定(bind)切换,例如
<mat-slide-toggle [id]="not.id" class="example-margin" [color]="color"
[checked]="not.isFinished" [(ngModel)]="not.isFinished"[disabled]="not.isFinished" (change)="onChange($event)" >
</mat-slide-toggle>
然后在保存方法中
onSave(){
this.notifications.forEach((n)=>{
console.log(n.id) //this is the id of your toggle
console.log(n.isFinished)//this is the value of toggle
})
}
更新
根据您的评论,您不想使用 ngModel
在这种情况下,您可以检查切换元素是否包含 mat-checked
类作为 Angular Material 添加检查类如果切换处于事件状态,请删除 ngmodel 并将方法更改为
onSave(){
this.notifications.forEach((n)=>{
console.log(n.id) //this is the id of your toggle
var ele=document.getElementById(n.id)
console.log(ele.classList.contains('mat-checked'))//this is the value
of toggle
})
}
关于javascript - 如何获取所有 Slide-Toggle 元素的 ID 和 Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58110739/