Angular Calendar 6 - Calendar does not display events on first load

Asked

Viewed 876 times

1

The calendar shows no events on the first load. Only when I trigger any event like clicking the button to change the month-to-week view, for example.

I’m using the Angular Calendar 6+
LINK

My design is done in Angular 6. The calendar does not show data on the first load, only after I trigger any element on screen.

Can anyone help in understanding why only on the first load the calendar is not filled?

HTML ...

<div [ngSwitch]="view">
          <mwl-calendar-month-view *ngSwitchCase="CalendarView.Month" [viewDate]="viewDate" [events]="events"
            [refresh]="refresh" [activeDayIsOpen]="activeDayIsOpen" (dayClicked)="dayClicked($event.day)"
            (eventClicked)="handleEvent('Clicked', $event.event)" (eventTimesChanged)="eventTimesChanged($event)"
            [locale]="locale" [weekStartsOn]="weekStartsOn" [weekendDays]="weekendDays" >
          </mwl-calendar-month-view>
          <mwl-calendar-week-view *ngSwitchCase="CalendarView.Week" [viewDate]="viewDate" [events]="events"
            [refresh]="refresh" (eventClicked)="handleEvent('Clicked', $event.event)"
            (eventTimesChanged)="eventTimesChanged($event)" [locale]="locale" [weekStartsOn]="weekStartsOn"
            [weekendDays]="weekendDays" (beforeViewRender)="beforeMonthViewRender($event)">
          </mwl-calendar-week-view>
          <mwl-calendar-day-view *ngSwitchCase="CalendarView.Day" [viewDate]="viewDate" [events]="events"
            [refresh]="refresh" (eventClicked)="handleEvent('Clicked', $event.event)"
            (eventTimesChanged)="eventTimesChanged($event)" [locale]="locale" >
          </mwl-calendar-day-view>
        </div>

TYPESCRIPT

import {
  Component,
  ChangeDetectionStrategy,
  ViewChild,
  TemplateRef,
  OnInit
} from "@angular/core";
import {
  CalendarEvent,
  CalendarView,
  DAYS_OF_WEEK,
  CalendarEventAction,
  CalendarEventTimesChangedEvent,
  CalendarDateFormatter
} from "angular-calendar";
import { NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { Subject, Observable } from "rxjs";
import {
  isSameDay,
  isSameMonth} from "date-fns";
import { HomeService } from "../shared/service/home.service";
import { CalendarioEvento } from "../shared/model/calendario-eventos.model";
import { FormGroup, FormBuilder } from "@angular/forms";
import { CustomDateFormatter } from "../shared/service/custom-date-formatter.provide";


@Component({
  selector: "mwl-demo-component",
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: "./home.component.html",
  styleUrls: ["./home.component.css"],
  providers: [
    HomeService,
    {
      provide: CalendarDateFormatter,
      useClass: CustomDateFormatter
    }
  ]
})
export class HomeComponent implements OnInit {
  @ViewChild("modalContent") modalContent: TemplateRef<any>;

  activeDayIsOpen: boolean = true;
  view: CalendarView = CalendarView.Month;
  viewDate: Date = new Date();
  locale: string = "pt-PT";
  modalData: {
    action: string;
    event: CalendarEvent;
  };
  weekStartsOn: number = DAYS_OF_WEEK.MONDAY;
  weekendDays: number[] = [DAYS_OF_WEEK.FRIDAY, DAYS_OF_WEEK.SATURDAY];
  CalendarView = CalendarView;
  listEvents: CalendarioEvento[] = [];
  evento: CalendarioEvento;
  eventsJson: string;
  filtroForm: FormGroup;
  botao: string;
  acaoPermitida: boolean;
  events: CalendarEvent[] = [];

  events$: Observable<Array<CalendarEvent<{ event: any }>>>;

  constructor(
    private modal: NgbModal,
    private homeService: HomeService  ) {}

  actions: CalendarEventAction[] = [
    {
      label: '<i class="fa fa-fw fa-pencil"></i>',
      onClick: ({ event }: { event: CalendarEvent }): void => {
        this.handleEvent("Edited", event);
      }
    },
    {
      label: '<i class="fa fa-fw fa-times"></i>',
      onClick: ({ event }: { event: CalendarEvent }): void => {
        this.events = this.events.filter(iEvent => iEvent !== event);
        this.handleEvent("Deleted", event);
      }
    }
  ];

  refresh: Subject<any> = new Subject();
  ngOnInit() {
    this.myMethodToInit();
  }

  myMethodToInit() {
    this.homeService.getAll().subscribe(data => {

      this.listEvents = data;

      this.listEvents.forEach(element => {
        var diaInicial = element.dataInicio.toString().substring(0, 2);
        var diaFim = element.dataFim.toString().substring(0, 2);
        var mesInicial = element.dataInicio.toString().substring(3, 5);
        var mesFim = element.dataFim.toString().substring(3, 5);
        var anoInicial = element.dataInicio.toString().substring(6, 10);
        var anoFim = element.dataFim.toString().substring(6, 10);
        var dataInicio = anoInicial + "-" + mesInicial + "-" + diaInicial;
        var dataFim = anoFim + "-" + mesFim + "-" + diaFim;
        let eve: CalendarEvent = {
          title: element.descricao,
          start: new Date(dataInicio),
          id: element.id,
          end: new Date(dataFim),
          actions: this.actions
        };
        this.events.push(eve);
      });
    });
  }

  dayClicked({ date, events }: { date: Date; events: CalendarEvent[] }): void {
    if (isSameMonth(date, this.viewDate)) {
      this.viewDate = date;
      if (
        (isSameDay(this.viewDate, date) && this.activeDayIsOpen === true) ||
        events.length === 0
      ) {
        this.activeDayIsOpen = false;
      } else {
        this.activeDayIsOpen = true;
      }
    }
  }

  eventTimesChanged({
    event,
    newStart,
    newEnd
  }: CalendarEventTimesChangedEvent): void {
    this.events = this.events.map(iEvent => {
      if (iEvent === event) {
        return {
          ...event,
          start: newStart,
          end: newEnd
        };
      }
      return iEvent;
    });
    this.handleEvent("Dropped or resized", event);
  }

  handleEvent(action: string, event: CalendarEvent): void {
    event.start = event.start;
    this.modalData = { event, action };
    this.modal.open(this.modalContent, { size: "lg" });
    document
      .getElementsByTagName("ngb-modal-window")
      .item(0)
      .setAttribute("id", "modal");
    document.getElementById("modal").style.opacity = "1";
  }

  addEvent(action: string, event: CalendarEvent): void {
    this.modalData = { event, action };
    this.modal.open(this.modalContent, { size: "lg" });
    document
      .getElementsByTagName("ngb-modal-window")
      .item(0)
      .setAttribute("id", "modal");
    document.getElementById("modal").style.opacity = "1";
  }

  deleteEvent(eventToDelete: CalendarEvent) {
    this.events = this.events.filter(event => event !== eventToDelete);
  }

  setView(view: CalendarView) {
    this.view = view;
  }

  closeOpenMonthViewDay() {
    this.activeDayIsOpen = false;
  }

  resetar() {}

  salvar() {
    console.log("titulo:" + this.modalData.event.title);
    console.log("start:" + this.modalData.event.start);
    console.log("end:" + this.modalData.event.end);
  }
}

FIRST SHIPMENT inserir a descrição da imagem aqui

AFTER TRIGGERING SOME EVENT inserir a descrição da imagem aqui

  • Good afternoon, how did you manage to put the calendar to Portuguese?

1 answer

1

Problem solved after a few hours rs.

Only 2 adjustments in Component.ts!

1st Include: encapsulation: Viewencapsulation.None

selector: "calendario-ico",
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: "./calendario.component.html",
  styleUrls: ["./calendario.component.css"],
  encapsulation: ViewEncapsulation.None,
  providers: [

2º Inside ngOnInit, after recovering all events, update the calendar with the command: this.refreshnext. ();

ngOnInit() {
    this.AtivarFormulario();
    this.homeService.getAll("", "", "").subscribe(data => {
      this.listEvents = data;
      this.listEvents.forEach(element => {
        var diaInicial = element.dataInicio.toString().substring(0, 2);
        var diaFim = element.dataFim.toString().substring(0, 2);
        var mesInicial = element.dataInicio.toString().substring(3, 5);
        var mesFim = element.dataFim.toString().substring(3, 5);
        var anoInicial = element.dataInicio.toString().substring(6, 10);
        var anoFim = element.dataFim.toString().substring(6, 10);
        var dataInicio = anoInicial + "-" + mesInicial + "-" + diaInicial;
        var dataFim = anoFim + "-" + mesFim + "-" + diaFim;
        let eve: CalendarEvent = {
          title: element.descricao,
          start: new Date(dataInicio),
          id: element.id,
          end: new Date(dataFim),
          actions: this.actions
        };
        this.events.push(eve);
      });
      this.refresh.next();
    });
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.