[Fixed] How can I view script function value in html block in Angular application?

Issue

I want to show "timeStops" value in html block from the script.

"timeStops" is output as array and I want to show this array value in html block.

Output of timeStops:

[
"21:00",
"21:30",
"22:00",
"22:30",
"23:00",
"23:30",
"00:00",
"00:30",
"01:00",
"01:30",
"02:00",
"02:30",
"03:00",
"03:30",
"04:00",
"04:30"
]

My Code:

<script>
  function getTimeStops(start, end) {
      var startTime = moment(start, 'HH:mm');
      var endTime = moment(end, 'HH:mm');

      if (endTime.isBefore(startTime)) {
        endTime.add(1, 'day');
      }

      var timeStops = [];

      while (startTime <= endTime) {
        timeStops.push(new moment(startTime).format('HH:mm'));
        startTime.add(15, 'minutes');
      }
      return timeStops;
    }

    var timeStops = getTimeStops('11:00', '02:00');
    console.log('timeStops ', timeStops);
    timeStops = getTimeStops('11:00', '23:59'); //Want to show this timeStops in html block
    console.log('timeStops ', timeStops);
</script>


<div>
  <p>I want to show "timeStops" value here from above script</p>
</div>

Solution

Please update app.component.ts like

import { Component } from '@angular/core';
import * as moment from "moment";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  getTimeStops(start: any, end: any) {
    var startTime = moment(start, 'HH:mm');
    var endTime = moment(end, 'HH:mm');

    if (endTime.isBefore(startTime)) {
      endTime.add(1, 'day');
    }

    var timeStops = [];

    while (startTime <= endTime) {
      timeStops.push(moment(startTime).format('HH:mm'));
      startTime.add(15, 'minutes');
    }
    return timeStops;
  }
  timeStops = this.getTimeStops('11:00', '02:00')
}

And your add this line in your app.component.html

*ngFor loop will display values individually

<div>{{timeStops | json}}</div>

<ul>
    <li *ngFor="let time of timeStops; let index = index">{{ time }}</li>
</ul>

Leave a Reply

(*) Required, Your email will not be published