javascript - angular2如何双向绑定多个checkbox?
问题描述
比如我又一个数组如下:
var array = [’喜欢’,’不喜欢’,’非常喜欢’,’超级喜欢’,’喜欢得不得了’];
html模板中
<p *ngFor='let e of array'> <input type='checkbox' name='like' value='{{e}}'></p><p class='youselect'></p>
我盖如何实现,选中其中一个checkbox后,能在p.youselect中显示出我已经选中的内容,如果是多选,则呈现出数组或者以逗号隔开的形式
比如我选中了“喜欢”,“喜欢得不得了”,那么p.youselect中则显示出:“喜欢,喜欢得不得了”
可以使用formArray等方式进行,但是我在使用过程中都没有实现。希望大神出手帮帮忙!
问题解答
回答1:谢邀,基于你给的数据结构,但建议还是使用如下数据结构(表单提交的时候,一般提交的对应的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'> <p *ngFor='let like of likes.controls; let i = index;' > <input type='checkbox' [formControl]='like'> {{likesArr[i]}} </p> <p class='youselect'>{{selects}}</p> </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’); }}回答2:
个人感觉不用 Forms 好像更简单吧。。。写了一个 Fiddle: https://jsfiddle.net/phnjg6hf/4/
HTML:
<test-component></test-component><script type='text/plain'> <p>Result: {{result()}}</p> <p *ngFor='let w of arr'><label> <input type='checkbox' value='{{w}}' [checked]='selections[w]' (change)='handle($event)' /> {{w}}</label> </p></script>
JS:
var Thing = ng.core.Component({ selector: 'test-component', template: document.getElementById('some').innerHTML})(function () { this.selections = { First: true }; this.arr = ['First', 'Second', 'Third'];});Thing.prototype.result = function () { var that = this; return this.arr.filter(function (x) {return that.selections[x]; }).join(', ');};Thing.prototype.handle = function (e) { var t = e.target, v = t.value, c = t.checked; this.selections[v] = c;};var AppModule = ng.core.NgModule({ imports: [ng.platformBrowser.BrowserModule], declarations: [Thing], bootstrap: [Thing], providers: []})(function () { });ng.platformBrowserDynamic.platformBrowserDynamic().bootstrapModule(AppModule);
相关文章:
1. mysql - 一个表和多个表是多对多的关系,该怎么设计2. html5 - iOS的webview加载出来的H5网页,怎么修改html标签select的样式字体?3. python 如何实现PHP替换图片 链接4. 一个mysql联表查询的问题5. angular.js - 三大框架react、vue、angular的分析6. mysql优化 - mysql count(id)查询速度如何优化?7. python如何不改动文件的情况下修改文件的 修改日期8. javascript - git clone 下来的项目 想在本地运行 npm run install 报错9. mysql主从 - 请教下mysql 主动-被动模式的双主配置 和 主从配置在应用上有什么区别?10. 主从备份 - 跪求mysql 高可用主从方案
