【发布时间】:2022-01-24 06:24:02
【问题描述】:
我有一个对象:
schedule = {
'Monday': { morning: { from: "9:00", to: "12:00" }, afternoon: { from: "15:00", to: "17:00" } },
'Tuesday': { morning: { from: "9:00", to: "12:00" }, afternoon: { from: "15:00", to: "17:00" } },
'Wednesday': { morning: { from: "9:00", to: "12:00" }, afternoon: { from: "15:00", to: "17:00" } },
'Thursday': { morning: { from: "9:00", to: "12:00" }, afternoon: { from: "15:00", to: "17:00" } },
'Friday': { morning: { from: "9:00", to: "12:00" }, afternoon: { from: "15:00", to: "17:00" } },
};
我将 schedule 对象转换为一个数组,以便 Angular 可以通过这种方式对其进行迭代:
getScheduleArray() {
let profile = this.profile;
var days = Object.keys(profile.schedule);
var array: { day: string; schedule: any; }[] = [];
days.map(function (key) {
return array.push({ day: key, schedule:profile.schedule[key] });
});
return array;
}
在我的 Angular 应用程序中,我有许多以这种方式动态生成的不同输入字段:
<div class="p-2" *ngFor="let day of getScheduleArray()">
<p><b>{{day.day}}</b></p>
<div class="row">
<p class="col">Morning</p>
<div class="col"><input class="form-control" type="text" placeholder="From" [(value)]="day.schedule.morning.from" (input)="updateSchedule(day.day, 'morning', 'from', $event)"></div>
<div class="col"><input class="form-control" type="text" placeholder="To" [(value)]="day.schedule.morning.to" (input)="updateSchedule(day.day, 'morning', 'to', $event)"></div>
</div>
<div class="row">
<p class="col">Afternoon</p>
<div class="col"><input class="form-control" type="text" placeholder="From" [(value)]="day.schedule.afternoon.from" (input)="updateSchedule(day.day, 'afternoon', 'from', $event)"></div>
<div class="col"><input class="form-control" type="text" placeholder="To" [(value)]="day.schedule.afternoon.to" (input)="updateSchedule(day.day, 'afternoon', 'to', $event)"></div>
</div>
</div>
要更新时间表,我使用以下方法:
updateSchedule(day: string, partOfDay: string, startOrFinish: string, event: any) {
this.profile.schedule[day][partOfDay][startOrFinish] = event.target.value;
}
有没有更好的方法来获得相同的结果?
【问题讨论】:
标签: javascript html angular typescript