将选中的复选框绑定到布尔值

时间:2018-07-05 14:49:41

标签: angular typescript web angular-fullstack

我正在用TypeScript使用angular 5。

我有一个对象,其中包含4个布尔值的数组,我试图将其绑定到4个复选框,它将创建表单,但是当我将数组的值记录到控制台时,它们似乎并没有改变我单击复选框。

HTML

<label  *ngFor = "let v of options[0].options; let i = index">
    <input type="checkbox"  [value]=options[0].values[index]  [checked]=options[0].values[index] (click)="options[0].log()">
    {{v}}
  </label>

component.ts

import {Component, NgModule, OnInit} from '@angular/core';
import {Param1} from '../classes';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})


@NgModule({
  imports: [
    FormsModule,
    ReactiveFormsModule
  ]})

export class TestComponent implements OnInit {

  options : Param1[];
  ids = [
          {id: 2, options:["a","b","c","d"], t:'single'},
          {id: 1, options:["a","b","c","d"], t:'multiple'},
          {id: 3, options:null, t:'open'},
  ];


  constructor() {
  }

  ngOnInit() {
    this.options = this.ids.map(function (value) {
      console.log(value);
      return new Param1(value.id, value.options, value.t);
    })
  }

  selectAction(id: string){
    console.log(id);
  }

  log(){console.log(1);}

}

param1对象:

export class Param1{
  id: number;
  options: string[];
  type: string;
  selected : string[];
  answer: string;
  values: boolean[];

  constructor(id: number, options: string[], t: string){
    this.id = id;
    this.options = options;
    this.type = t;

    if(options) {
      console.log("in the init" + options);
      this.values = options.map(function () {
        return false;
      });
    }

  }

  log(){
    console.log(this.values);
  }

  select(option: string){

    if (this.type == "single"){
      this.selected.pop();
    }

    this.selected.push(option);
    this.selected = Array.from(new Set(this.selected));
  }
}

我在这里想念什么?

1 个答案:

答案 0 :(得分:2)

这是一个有效的示例:

<div *ngFor="let option of options; let i = index">
  <h1>Param {{ i }}</h1>
  <div *ngFor="let booleanOption of option.options; let i = index">
    <label [attr.for]="booleanOption">Option {{ booleanOption }}</label>
    <input type="checkbox" [attr.id]="booleanOption" [(ngModel)]="option.values[i]" (change)="option.log()" />
  </div>
</div>

https://stackblitz.com/edit/angular-5-binding-checkbox-checked-to-boolean?file=src%2Fapp%2Fapp.component.html