1
+ /**
2
+ * Example using Angular ngFor to loop through items and create DOM items
3
+ */
4
+ import { Component , AfterViewInit , OnChanges , SimpleChanges , Input , ChangeDetectionStrategy } from '@angular/core' ;
5
+
6
+ import { GridStack , GridStackWidget } from 'gridstack' ;
7
+ import 'gridstack/dist/h5/gridstack-dd-native' ;
8
+
9
+ @Component ( {
10
+ selector : 'app-angular-ng-for-test' ,
11
+ template : `
12
+ <button (click)="add()">add item</button><button (click)="delete()">remove item</button><button (click)="change()">modify item</button>
13
+ <div class="grid-stack">
14
+ <!-- using angular templating to create DOM, otherwise an easier way is to simply call grid.load(items) -->
15
+ <div *ngFor="let n of items; let i = index" class="grid-stack-item" [attr.gs-w]="n.w" [attr.gs-h]="n.h" [attr.gs-x]="n.x" [attr.gs-y]="n.y">
16
+ <div class="grid-stack-item-content">item {{i}}</div>
17
+ </div>
18
+ </div>
19
+ ` ,
20
+ // gridstack.min.css and other custom styles should be included in global styles.scss
21
+
22
+ // tell Angular only @Input will change - doesn't help
23
+ // changeDetection: ChangeDetectionStrategy.OnPush
24
+ } )
25
+ export class AngularNgForTestComponent implements AfterViewInit , OnChanges {
26
+ @Input ( ) public items : GridStackWidget [ ] = [
27
+ { x : 0 , y : 0 , w : 9 , h : 6 } ,
28
+ { x : 9 , y : 0 , w : 3 , h : 3 } ,
29
+ { x : 9 , y : 3 , w : 3 , h : 3 } ,
30
+ ] ;
31
+ private grid : GridStack ;
32
+
33
+ constructor ( ) { }
34
+
35
+ // wait until after DOM is ready to init gridstack - can't be ngOnInit() as angular ngFor needs to run first!
36
+ public ngAfterViewInit ( ) {
37
+ this . grid = GridStack . init ( {
38
+ cellHeight : 70 ,
39
+ } ) ;
40
+ }
41
+
42
+ /**
43
+ * this would be easier with addWidget(), removeWidget(), update() but simulating angular change detection instead...
44
+ */
45
+ public add ( ) {
46
+ // this SHOULD trigger ngOnChanges() but not seeing it... and doing ngDoCheck() seem extreme ?
47
+ // https://www.reddit.com/r/angular/comments/azjefs/change_detection_for_arraysobjects/
48
+ // https://angular.io/guide/lifecycle-hooks#docheck
49
+ this . items = [ ...this . items , { x : 1 , y : 6 , w : 3 } ] ;
50
+ // this.items.push({x: 1, y: 6, w: 3});
51
+ }
52
+ public delete ( ) {
53
+ this . items . pop ( ) ; // todo
54
+ }
55
+ public change ( ) {
56
+ this . items [ 0 ] . w = 1 ; // todo
57
+ }
58
+
59
+ public ngOnChanges ( changes : SimpleChanges ) {
60
+ if ( changes . items ) {
61
+ // TODO: ... figure what is new and call makeWidget(), old -> removeWidget(el,false) and changed -> update()
62
+ console . log ( 'items changed' ) ;
63
+ }
64
+ }
65
+ }
66
+
0 commit comments