Angular 5显示基于数组检查的复选框

Rob*_*lls 2 angular

我有一组Angular形式的动态复选框:

<div class="form-check" *ngFor="let topic of topics">
    <input class="form-check-input" (change)="onChange(f)" #f type="checkbox" [value]="topic.name" name="topicgroup">
    <label class="form-check-label" style="font-weight: normal">
        {{topic.name}}
    </label>
</div>
Run Code Online (Sandbox Code Playgroud)

在我的编辑组件中,如何将它们设置为已选中?

我有一个包含所有选项的数组,以及检查哪个选项:

Topics: string[] = ['Topic1', 'Topic2', 'Topic3', 'Topic4', 'Topic5']; 
selectedTopics: string[] = ['Topic1', 'Topic2']; 
Run Code Online (Sandbox Code Playgroud)

我如何在我的html页面上反映出来?

更新:这是我的onChange函数:

onChange(f) {
if (this.selectedTopics.indexOf(f.value) == -1) {
  this.selectedTopics.push(f.value);
} else {
  this.selectedTopics.splice(this.selectedTopics.indexOf(f.value), 1);
}
Run Code Online (Sandbox Code Playgroud)

Arp*_*eti 5

首先,您topic.name按照您的阵列使用它将只是主题.

其次,添加[checked]属性以将其标记为已选中或未选中,如下所示.

<div class="form-check" *ngFor="let topic of topics">
    <input class="form-check-input" [checked]="topic in selectedTopics" (change)="onChange(topic)" #f type="checkbox" [value]="topic" name="topicgroup">
    <label class="form-check-label" style="font-weight: normal">
        {{topic}}
    </label>
</div> 
Run Code Online (Sandbox Code Playgroud)

第三,你的function onChange(topic)意愿如下

onChange(topic: string) {
  let index = this.selectedTopics.indexOf(topic);
  if (index == -1) {
    this.selectedTopics.push(value);
  } else {
    this.selectedTopics.splice(index, 1);
  }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE 替换[checked]="topic in selectedTopics"[checked] = isSelected(topic)

并在您的控制器中添加功能

isSelected(topic){
    return selectedTopics.indexOf(topic) >= 0;
}
Run Code Online (Sandbox Code Playgroud)