2017-05-04 53 views
0

我是新來Angular和使用NgFor,我顯示的元素,我想選擇他們,點擊我應該得到ID在組件功能。 但我嘗試使用ngModel和所有的按鈕被選中。在Angular 2 JS中,如何向組件中的函數發送複選框值?

我想在用戶選中框時獲取(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

這裏是一個簡單的例子:

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 {} 
+0

它的工作原理,但你能解釋我英雄在這裏做什麼?它的工作原理,但如果我明白,我會更有見識。他們如何溝通? newDate的用途是什麼? –

+0

哦,它只是一個簡單的數組..讓我用明確的數組更新答案:) –

+0

editied ..希望它現在有道理? –

相關問題