4

I am new to Angular and using NgFor, I am displaying elements which I want to select them, upon clicking I should get the ID in the Component function. But I tried using ngModel and all the buttons get selected.

I am trying to get the (hero.id) when the user checks the boxes. How do I do it? What are my mistakes.

My 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>

Here is my component.

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 Answer 1

6

here is a simple example:

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

to detect the user checked the box, you need to use the change event binding. then call your function and pass it that change $event. the $event here is crucial syntax. then you can access all kinds of things from that event, mainly the target which is the HTML element <input> that was changed.. then you'd get the id as it is the value of that input.

    //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 {}
Sign up to request clarification or add additional context in comments.

4 Comments

It works but can you please explain me what does heroes do here? It works but I will be more knowledgeable if I understand. So do they communicate? What is newDate for?
oh, it is just a simple array.. let me update the answer with an explicit array instead :)
Thankyou so much sir, a million upvotes you. You saved my day!
Thats why I always include the code in the answer :) should be easy to move it to a plunker or otherwise :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.