Я делаю генератор маршрута, все действия имеют свою продолжительность (в минутах), а маршрут имеет время начала, поэтому, когда я генерирую маршрут, я обновляю час в базе продолжительности действия и показываю обновленный час в следующем действии. Например, если маршрут начинается в 18:00, а время первого действия составляет 5 минут, это время будет добавлено к часу, и оно будет отображаться в HTML примерно так:
Но при обновлении времени вместо передачи его следующему действию оно добавляется к нему. Например:
Ми код:
Интерфейс активности:
export interface Activity{
activityName : string;
duration : number;
zone : string;
participants : Participante [];
time ?: Date
}
Компонент программы:
export class ProgramComponent {
program !: Program[]
startTime !: Date;
time !: Date; //It's the time I send and receive from child
constructor( private gpService: ProgramGeneratorServices ) {
//I save the start time from Form, don't show all the interfaces 'çause I don't think it's necessary
this.startTime = this.program[0].startTime;
this.time = this.programa[0].startTime;
}
//This function is only for reset the hour to start, I do two itinerary for 2 weeks so I need restart the hour for ngFor
resetHour() {
this.time = this.startTime
}
//This function update the hour inside this program component
updateMinutes( activity?: Activity ) {
this.time = this.gpService.addMinutes( this.time, activity?.duration);
}
//This function update the hour receiving the time from a child component
updateTime( updatedTime: Date ) {
this.time = updatedTime;
}
}
Программа html:
<div *ngFor = "let subPrograma of programa;"
class = "mb-5"> {{ resetHour() }}
<div class = "my-3">
<div class = "col-6 titulo_seccion ps-2">
{{ subProgram.sections[1].sectionName | uppercase }}
</div>
//Send the activity data and the time to child and returns the updated time to send to the next activity
<app-actividad
*ngFor = "let activity of subProgram.sections[1].activities"
[activity] = "activity"
[time] = "time"
(timeChange) = "updateTime($event)"
></app-actividad>
</div>
</div>
Приложение Activity (дочерний компонент):
export class ActividadComponent implements OnInit{
@Input() activity !: Actividad;
@Input() time !: Date;
@Output() timeChange = new EventEmitter<Date>();
constructor( private gpService: ProgramGeneratorService ) {
}
//In OnInit assign time to activity and next to update the time whit a services function
ngOnInit(): void {
this.activity.time = this.time;
this.addMinutes();
}
addMinutes(): void {
this.time = this.gpService.addMinutes( this.time, this.activity.duration);
this.timeChange.emit( this.time );
}
}
Активность HTML (дочерняя)
<div class = "row">
<div class = "col-4">
<div class = "row">
<div class = "col text-start">
<span> {{ time | date: 'hh:mm' }}
<span class = "cr">
<span class = "point">•</span>
//THIS is where I print the time
{{ activity.activityName }}
<span *ngIf = "activity.time > 0" class = "ms-1">
({{ activity.time }} mins)
</span>
</span>
</span>
</div>
</div>
</div>
</div>
Услуги генератора программ:
export class GeneradorProgramaService {
constructor( private http: HttpClient ) { }
//This is the function that updates the time
addMinutes( currentTime: Date, mins: number = 5 ): Date {
return new Date( currentTime.getTime() + mins * 60000 );
}
}
Надеюсь, кто-нибудь может мне помочь, я застрял на несколько часов (если вы видите что-то странное, это потому, что я пропустил код, который я считаю ненужным, и поместил только часть, связанную с проблемой).
Вы используете time
в HTML и переопределяете time
в функции addMinutes
в дочернем компоненте.
...
ngOnInit(): void {
this.activity.time = this.time;
this.addMinutes();
}
addMinutes(): void {
// Here, you override the time. That's why you see the weird one in the HTML.
this.time = this.gpService.addMinutes( this.time, this.activity.duration);
this.timeChange.emit( this.time );
}
addMinutes_NoOverride() {
// Store the new time in a const and then emit it.
const newTime = this.gpService.addMinutes(this.time, this.activity.duration);
this.timeChange.emit(newTime);
}
Можете ли вы создать stackblitz, чтобы у нас была одна и та же база