0

i am working with date and time. i have calendar and default time slots from 9am to 5pm. i need to mark checked property to true in timeList parameter by mathcing time from the selectedDatesTiming paramters. but it updates same timing in staticTime variable as well. I am not able understand the behaviour. As i am updating only timeList parameter by comparing with selectedDatesTiming parameter. Please give some solutions.

 import { Component } from '@angular/core';

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

 timeList: any = [
    { id: 1, checked: false, time: '09:00 am' },
    { id: 2, checked: false, time: '10:00 am' },
    { id: 3, checked: false, time: '11:00 am' },
    { id: 4, checked: false, time: '12:00 am' },
    { id: 5, checked: false, time: '01:00 pm' },
    { id: 6, checked: false, time: '02:00 pm' },
    { id: 7, checked: false, time: '03:00 pm' },
    { id: 8, checked: false, time: '04:00 pm' },
    { id: 9, checked: false, time: '05:00 pm' },
  ];

   staticTime: any = [
    { id: 1, checked: false, time: '09:00 am' },
    { id: 2, checked: false, time: '10:00 am' },
    { id: 3, checked: false, time: '11:00 am' },
    { id: 4, checked: false, time: '12:00 am' },
    { id: 5, checked: false, time: '01:00 pm' },
    { id: 6, checked: false, time: '02:00 pm' },
    { id: 7, checked: false, time: '03:00 pm' },
    { id: 8, checked: false, time: '04:00 pm' },
    { id: 9, checked: false, time: '05:00 pm' },
  ];

  selectedDatesTiming: any = [
    {time:'09:00 am'},
    {time:'10:00 am'}
  ]

ngOnInit(){
  this.show();
}

show(){

   this.timeList = null;

   setTimeout(() => {

        this.timeList = this.staticTime;

        for (let index = 0; index < this.timeList.length; index++) {
          for (let index1 = 0; index1 < this.selectedDatesTiming.length; index1++) {
            if (this.selectedDatesTiming[index1].time === this.timeList[index].time) {
              this.timeList[index].checked = true;
            }
          }
        }

        console.log(this.staticTime);
        console.log(this.timeList);
      }, 500);
}

}

https://stackblitz.com/edit/settimeout-ay4l3b?file=app%2Fapp.component.ts

Gobind Gupta
  • 203
  • 3
  • 13

1 Answers1

2

Try to this ..

Remove this line from your code.

this.timeList = this.staticTime;

And add this line..

this.timeList = JSON.parse(JSON.stringify(this.staticTime));
Rohit Tagadiya
  • 3,373
  • 1
  • 25
  • 25