1

in my application I have a Dashboard where the user can add and delete widgets. To do so I am using angular-gridster2. This works well, but when I am adding or deleting a widget from the dashboard first no widgets are displayed anymore and then only after a refresh the correct changes occur. My Widget list the ngFor directive is iterating through is build from an observable. These values change correctly.

This is my html:


<gridster #dashboardgrid [options]="options" class="widget-container">
    <gridster-item *ngFor="let widget of widgetList()" (mouseup)="setCurrentWidgetId(widget.id)" [item]="widget.position" class="gridster-design drag-handler">
      <!-- some stuff-->
    </gridster-item>
</gridster>

In my ngOnInit I am subscribing from the observable:

    this.dataService.currentDashboardId.subscribe(dashboardId => this.currentDashboardId = dashboardId);
    this.dataService.currentSheetId.subscribe(sheetId => this.currentSheetId = sheetId);
    this.dataService.projectData
      .subscribe((project: Project) => {
        this.project = project;
  });

And this is the method returning the list of widgets which should be displayed:

    widgetList(): Array<Widget> {
    return this.project.dashboards
      .find(x => x.id === this.currentDashboardId).sheets
      .find(x => x.id === this.currentSheetId).widgets;
  }

I really can't find the reason for this behaviour so if anybody does I appreciate that. Thanks in advance.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Chinaedu Onwukwe
  • 437
  • 1
  • 7
  • 20
  • You could try using a custom trackby function, did you try it ? –  Oct 23 '18 at 07:14
  • Keep your widgetList() under ngOnInit(), store return value to a list and use that list with *ngFor. This way you are iterating just a return value of a function that is why it is not reflecting on update. – Vishw Patel Oct 23 '18 at 07:16

2 Answers2

1

Did you try to debug it? Try to change the foreach loop to a list, instead of a function

*ngFor="let widget of widgetList()"

*ngFor="let widget of list"

and in your ngOnInit:

this.list = this.widgetList()

this way you can debug it and see if your list contains any items. If it does, then I would look deeper into your gridster-item component and make sure that the [item]="widget.position" has value according to the component logic

Dima Shivrin
  • 99
  • 2
  • 11
0

store the array in some variable let say widgetList

widgetList : any;
widgetList(): Array<Widget> {
return this.widgetList = this.project.dashboards
  .find(x => x.id === this.currentDashboardId).sheets
  .find(x => x.id === this.currentSheetId).widgets;
}

and use ngfor in html like this

*ngFor="let widget of widgetList"
khan Farman
  • 346
  • 3
  • 11