首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何检索所有复选框?

如何检索所有复选框?
EN

Stack Overflow用户
提问于 2019-03-04 16:25:32
回答 3查看 1.9K关注 0票数 1

我定义了一些带有角材料复选框组件的复选框:https://material.angular.io/components/checkbox/examples

代码语言:javascript
运行
复制
<div>
  <mat-checkbox formControlName="authors" class="authors-checkboxes" *ngFor="let author of authors" [value]=author.id>{{ author.name }}</mat-checkbox>
</div>

和一个FormGroup

代码语言:javascript
运行
复制
this.form = new FormGroup({
  id: new FormControl(article.id),
  timestamp: new FormControl(article.timestamp),
  title: new FormControl(article.title),
  chapo: new FormControl(article.chapo),
  body: new FormControl(article.body),
  bodyStyle: new FormControl(article.bodyStyle),
  author: new FormControl(article.author),
  authors: new FormControl(article.authors),
  authors2: new FormControl(article.authors2),
  date: new FormControl(article.date),
  readingTime: new FormControl(article.readingTime),
  pictures: new FormControl(),
  status: new FormControl(),
  mainPicture: new FormControl(article.mainPicture),
  mainPictureFile: new FormControl(article.mainPictureFile),
  position: new FormControl(article.position)
});

获得所有点击复选框的最佳方法是什么?我想收集所有选定的作者。

我正在考虑用document.getElementsByClassName和forEach来做这件事,但是我觉得这不是一个好方法。

代码语言:javascript
运行
复制
const authorsCheckboxes = document.getElementsByClassName("authors-checkboxes");
console.log(authorsCheckboxes);
Array.prototype.forEach.call(authorsCheckboxes, function(authorCheckbox) {
  console.log(authorCheckbox);
  console.log(authorCheckbox.value);
});
EN

Stack Overflow用户

发布于 2019-03-04 16:47:11

选项1

向author类添加isSelected属性,并在复选框上使用双向绑定。然后,可以根据选定的状态对作者列表进行筛选。

代码语言:javascript
运行
复制
<mat-checkbox *ngFor="let author of authors" [(ngModel)]="author.isSelected"></mat-checkbox>

Stackblitz演示:https://stackblitz.com/angular/mxvrpgjvnba

authors.filter(a=>a.isSelected);

选项2

使用复选框的change事件跟踪所选作者。可以将选定的作者保留在数组中,并对change事件进行添加/删除。

change: EventEmitter<MatCheckboxChange>

选项3

或者,您可以查看选择列表:

https://material.angular.io/components/list/overview#selection-lists

显示选定选项的演示:

https://stackblitz.com/angular/rmxjxxaoode?file=app%2Flist-selection-example.ts

票数 2
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54987429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档