How to bind multiple checkboxes bidirectionally in angular2?
高洛峰
高洛峰 2017-06-26 10:55:43
0
2
1013

For example, I have another array as follows:

var array = ['喜欢','不喜欢','非常喜欢','超级喜欢','喜欢得不得了'];

html template

<p class="like" *ngFor="let e of array">
    <input type="checkbox" name="like" value="{{e}}">
</p>
<p class="youselect"></p>

How do I implement it? After selecting one of the checkboxes, the selected content can be displayed in p.youselect. If it is multiple selection, it will be displayed as an array or comma separated form

For example, if I select "Like", "I like it very much", then p.youselect will display:
"I like it, I like it very much"

You can use formArray and other methods, but I didn't implement it during use. I hope God can help!

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
我想大声告诉你

Thank you for the invitation. Based on the data structure you gave me, it is recommended to use the following data structure (when submitting the form, the corresponding id item is generally submitted):

[ 
   { name: '喜欢',  selected: true, id: 0 },
   { name: '不喜欢', selected: false, id: 1 }
]

For details, please refer to - handling-multiple-checkboxes-in-angular-forms

The simple sample code is as follows:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
   <form [formGroup]="myForm">
    <p class="like" *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');
  }

}
学霸

Personally, I feel like it’s easier not to use Forms. . .
Written a Fiddle: https://jsfiddle.net/phnjg6hf/4/

HTML:

<test-component></test-component>
<script id="some" 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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template