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);
}
}
它的工作原理,但你能解釋我英雄在這裏做什麼?它的工作原理,但如果我明白,我會更有見識。他們如何溝通? newDate的用途是什麼? –
哦,它只是一個簡單的數組..讓我用明確的數組更新答案:) –
editied ..希望它現在有道理? –