javascript - angular2如何双向绑定多个checkbox?
本文介绍了javascript - angular2如何双向绑定多个checkbox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
比如我又一个数组如下:
var array = ['喜欢','不喜欢','非常喜欢','超级喜欢','喜欢得不得了'];
html模板中
<div class="like" *ngFor="let e of array">
<input type="checkbox" name="like" value="{{e}}">
</div>
<div class="youselect"></div>
我盖如何实现,选中其中一个checkbox后,能在div.youselect中显示出我已经选中的内容,如果是多选,则呈现出数组或者以逗号隔开的形式
比如我选中了喜欢,喜欢得不得了,那么div.youselect中则显示出:
喜欢,喜欢得不得了
可以使用formArray等方式进行,但是我在使用过程中都没有实现。希望大神出手帮帮忙!
解决方案
谢邀,基于你给的数据结构,但建议还是使用如下数据结构(表单提交的时候,一般提交的对应的id项):
[
{ name: '喜欢', selected: true, id: 0 },
{ name: '不喜欢', selected: false, id: 1 }
]
具体可以参考 - handling-multiple-checkboxes-in-angular-forms
简单的示例代码如下:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<form [formGroup]="myForm">
<div class="like" *ngFor="let like of likes.controls; let i = index;" >
<input type="checkbox" [formControl]="like">
{{likesArr[i]}}
</div>
<div class="youselect">{{selects}}</div>
</form>
`,
})
export class AppComponent implements OnInit{
myForm: FormGroup;
likesArr: string[] = ['喜欢','不喜欢','非常喜欢','超级喜欢','喜欢得不得了'];
selects: string[] = ['喜欢'];
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
likes: this.fb.array([true, false, false, false, false])
});
this.likes.valueChanges.subscribe(values => {
let selects: string[] = [];
values.forEach((selected: boolean ,i: number) => {
selected === true && selects.push(this.likesArr[i])
});
this.selects = selects;
});
}
get likes () {
return this.myForm.get('likes');
}
}
这篇关于javascript - angular2如何双向绑定多个checkbox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文