【问题标题】:Angular(2/4/5/6) Convert array of timeslots into time rangeAngular(2/4/5/6)将时隙数组转换为时间范围
【发布时间】:2019-04-24 10:32:27
【问题描述】:

您好,感谢您的所有回答!这是我根据您的输入更新的解决方案。谢谢!

getTime(apptTime) {
   const fields = apptTime.split("-");
   const startingTime = this.formatTime(+fields[0]);
   const endingTime = this.formatTime(+fields[1]);

   return startingTime + " - " + endingTime;
}

formatTime(time) {
    if (time < 12) {
      return time === 0 ? "12am" : time + "am";
    } else {
      return time === 12 ? time + "pm" : time - 12 + "pm";
    }
  }

我有一个字符串数组 => appt_timeslots = ["09-12", "12-15", "15-18", "18-21"] 从后端检索到的内容,我想将其显示为单选按钮,如下所示:

appt.component.html

<ng-container *ngFor="let appt of appt_timeslots" [ngSwitch]="appt">
   <label ngbButtonLabel class="btn btn-secondary active btn-radio btn-color">
      <input ngbButton type="radio" name="timeslot" value="{{ appt }}"/>
         <span *ngSwitchCase="'09-12'">9am - 12pm</span>
         <span *ngSwitchCase="'12-15'">12pm - 5pm</span>
         <span *ngSwitchCase="'15-18'">3pm - 6pm</span>
         <span *ngSwitchCase="'18-21'">6pm - 9pm</span>
   </label>
</ng-container>

有没有更好的方法来获取我的时间段,以便我可以显示 am/pm 和破折号,而不是使用 switch case?
这样它也可以满足其他时间段的需求(例如下午 2 点 - 下午 4 点),我不必手动添加另一个开关盒来满足新的需求。
感谢您的帮助!

【问题讨论】:

  • 也许是打字稿中的时间映射。使用键 = appt_timeslots 值和值 = 9am - 12pm 字符串制作字典。例如。 {"09-12":"9am - 12pm", ...}。那么你可以做 {{dict[appt]}}
  • 现在有时间,我可以这样做stackblitz.com/edit/angular-ngmodel-form-8hyfqc,如果对您有帮助,请根据您的要求扩展它..

标签: angular string switch-statement


【解决方案1】:

这是一种可能的方法。

首先我按原样存储后端数据。

然后我将创建一个以后端数据为值并基于该值显示文本的对象。例如对于后端数组'09-12'的一个元素,我创建一个对象{value:'09-12', text: '9am-12pm'}

你的 ts 文件:

 backendData =  ["09-12", "12-15", "15-18", "18-21"] //Data from the backend
 appt_timeslots = []  //This will be our object

 //I do the rest in ngOnInit but that's just for the example.
 ngOnInit() { 

    this.backendData.forEach(e => {
      var text = this.getTextFromValue(e);
      this.appt_timeslots.push({value: e, text: text});
    })
    console.log(this.appt_timeslots);
  }

 getTextFromValue(value:string){

    var timeSlots = value.split("-");
      var formattedTime = timeSlots.map(time => {
        time = this.setAMorPM(time);
        return time
      });

      var result = formattedTime.join("-")
      return result
  }

  setAMorPM(number: string){

    if(parseInt(number) > 12)
      number = (parseInt(number) - 12).toString() + 'pm';
    else
      if(parseInt(number) == 0)
        number = "12am"
      else  
        if(number[0]=='0')
        {
          number = number.slice(1);
          number += 'am';
        }

    return number
  }

我们根据每个元素的后端数据创建一个对象,并将其推送到对象数组 (appt_timeslots )。

getTextFromValue()toAMorPM() 这两个函数仅用于根据值创建文本,为了便于阅读,我将它们分开。

您的 HTML 文件:

现在您只需要遍历对象数组并在需要时插入值或文本,如下所示:

<ng-container *ngFor="let appt of appt_timeslots" [ngSwitch]="appt.value">
  <label ngbButtonLabel class="btn btn-secondary active btn-radio btn-color">
     <input ngbButton type="radio" name="timeslot" value="{{ appt.value }}"/>
        <span *ngSwitchCase="appt.value">{{appt.text}}</span>
  </label>
</ng-container>

注意:函数可能可以写得更简洁,但我认为这种方法是有意义的。

【讨论】:

    【解决方案2】:

    我喜欢使用 Pipe 进行转换,这个没有格式检查,但对你有用

        import { Pipe, PipeTransform } from '@angular/core';
    
        @Pipe({
          name: 'timeslot'
        })
        export class TimeslotPipe implements PipeTransform {
    
          transform(value: string): any {
            const times = value.split('-');
            return `${this.generateTimeString(times[0])} - ${this.generateTimeString(times[1])}`;
          }
    
          private generateTimeString(hourValue: string): string {
            const suffix = +hourValue - 12 > -1 ? 'pm' : 'am';
            const twelveFormat = +hourValue - (suffix === 'pm' ? 12 : 0);
            return `${twelveFormat}${suffix}`;
          }
        }
    

    和.html

    <p *ngFor="let slot of timeslots">{{slot | timeslot}}</p>
    

    【讨论】:

      猜你喜欢
      • 2018-04-17
      • 1970-01-01
      • 2019-11-20
      • 2019-10-03
      • 2020-07-29
      • 2017-08-05
      • 2019-01-13
      • 2021-08-26
      • 2010-10-15
      相关资源
      最近更新 更多