在Angular 2中,如何将Checkbox值发送到组件中的函数?

时间:2017-05-04 19:10:08

标签: angular

我是Angular的新手并使用NgFor,我正在显示我想要选择它们的元素,点击后我应该在Component函数中获取ID。 但是我尝试使用ngModel并且所有按钮都被选中了。

我试图在用户选中框时获取(hero.id)。我该怎么做?我的错误是什么。

  

我的HTML

<div>
  <form (submit)="onSubmit()">
    <tr *ngFor="let hero of heroes">
      <input type="checkbox" name="timeid" value={ {hero.id}} class={{hero.id}}>{{hero.time}}<br>
    </tr>
    <input type="submit" class="btn btn-primary" value="Remove Alarms">
  </form>
</div>
  

这是我的组件。

import { Component, OnInit } from '@angular/core';
import {ValidateService} from '../../services/validate.service';
import {AlarmService} from '../../services/alarm.service';
import {FlashMessagesService} from 'angular2-flash-messages';
import {Router} from '@angular/router';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  hours;
  id: String;
  timeid: String;
  time;
  heroes: any[];


  constructor(
    private validateService: ValidateService,
    private FlashMessage: FlashMessagesService,
    private Router: Router,
    private AlarmService: AlarmService
  ) {


  }

  ngOnInit() {

    this.ui();
  }

  onRegisterSubmit() {

    this.ui();

    this.heroes = JSON.parse(localStorage.getItem('users'));

    var timeStr = new Date(this.hours);
    var date = new Date(timeStr);
    var day = date.getUTCDate();
    var year = date.getUTCFullYear();
    var month = date.getUTCMonth() + 1;
    var hour = date.getUTCHours();
    var minutes = date.getUTCMinutes();
    var dateStr = "Time is " + hour + ":" + minutes + " in 24 HRS Time and the Date is " + day + "/" + month + "/" + year;

    console.log(dateStr);

    var user = {
      hours: (new Date(this.hours.replace('T', ' ').replace('-', '/'))).valueOf(),
      id: new Date().getTime(),
      time: dateStr,
      flag: 0,
    }


    setTimeout(() => {
      this.FlashMessage.show('Your alarm has been added.', {
        cssClass: 'alert-success',
        timeout: 5000
      });
    }, 10);

    var storage = localStorage.getItem('users');
    var final = [];
    if (storage == null || typeof(storage) == undefined) {
      final.push(user);

      localStorage.setItem('users', JSON.stringify(final));
      let time = new Date().getTime()

      this.AlarmService.setUpAlarms(time);

    } else {
      var get = JSON.parse(localStorage.getItem('users'));
      var size = Object.keys(get).length;

      for (var i = 0; i < get.length; i++) {
        final.push(get[i]);
      }
      final.push(user);
      localStorage.setItem('users', JSON.stringify(final));
      let time = new Date().getTime()

      this.AlarmService.setUpAlarms(time);
    }

  }


  ui() {
    setTimeout(() => {
      this.heroes = JSON.parse(localStorage.getItem('users'));
      console.log(this.heroes);
    }, 100);
  }

  onSubmit() {
    var user = {
      timeid: this.timeid,
    }
    console.log(user);

  }
}

1 个答案:

答案 0 :(得分:2)

这是一个简单的例子:

  

plunker:https://plnkr.co/edit/1nWBj5Z48vFYPOw6nbDa?p=preview

要检测用户选中该框,您需要使用change事件绑定。然后调用你的函数并传递它$event$event这里是至关重要的语法。那么你可以从那个事件中访问所有类型的东西,主要是target,它是被更改的HTML元素<input>。然后你得到了id,因为它是值输入

    //our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <div>
        <form>
          <tr *ngFor="let hero of heroes">
          <input (change)="check($event)" type="checkbox" name="timeid" value ="{{hero.id}}" class="{{hero.id}}">{{hero.time}}<br>
          </tr>
        </form>
      </div>
    </div>
  `,
})
export class App {
  name:string;
  // sample heros with an id and time..
  heroes =
    [
      {"id":1,"time":"2017-06-01T05:00:00.000Z"},
      {"id":2,"time":"2017-06-02T05:00:00.000Z"},
      {"id":3,"time":"2017-06-03T05:00:00.000Z"},
      {"id":4,"time":"2017-06-04T05:00:00.000Z"},
      {"id":5,"time":"2017-06-05T05:00:00.000Z"}
    ];
  constructor() {
    console.log(JSON.stringify(this.heroes))
    this.name = `Angular! v${VERSION.full}`
  }
  check(e){
    console.log(e)
    console.log(e.target.checked)
    console.log(e.target.value)
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}