I have some Angular 1 experience, but we have a need to use gridstack.js in an Angular 2 project.
We are familiar with the gridstack-angular project, but that proj
We ended up creating two directives: GridStackDirective and GridStackItemDirective -
grid-stack-directive.ts:
import { Directive, OnInit, Input, ElementRef, Renderer } from '@angular/core';
declare var $: any; // JQuery
@Directive({
selector: '[gridStack]'
})
export class GridStackDirective implements OnInit {
@Input() w: number;
@Input() animate: boolean;
constructor(
private el: ElementRef,
private renderer: Renderer
) {
renderer.setElementAttribute(el.nativeElement, "class", "grid-stack");
}
ngOnInit() {
let renderer = this.renderer;
let nativeElement = this.el.nativeElement;
let animate: string = this.animate ? "yes" : "no";
renderer.setElementAttribute(nativeElement, "data-gs-width", String(this.w));
if(animate == "yes") {
renderer.setElementAttribute(nativeElement, "data-gs-animate", animate);
}
let options = {
cellHeight: 80,
verticalMargin: 10
};
// TODO: listen to an event here instead of just waiting for the time to expire
setTimeout(function () {
$('.grid-stack').gridstack(options);
}, 300);
}
}
grid-stack-item-directive.ts:
import { Directive, ElementRef, Input, Renderer, OnInit } from '@angular/core';
@Directive({
selector: '[gridStackItem]'
})
export class GridStackItemDirective {
@Input() x: number;
@Input() y: number;
@Input() w: number;
@Input() h: number;
@Input() minWidth: number;
@Input() canResize: boolean;
constructor(
private el: ElementRef,
private renderer: Renderer
) {
renderer.setElementAttribute(el.nativeElement, "class", "grid-stack-item");
}
ngOnInit(): void {
let renderer = this.renderer;
let nativeElement = this.el.nativeElement;
let cannotResize: string = this.canResize ? "yes" : "no";
let elementText: string = '' + nativeElement.innerHTML + '';
// TODO: Find the Angular(tm) way to do this ...
nativeElement.innerHTML = elementText;
renderer.setElementAttribute(nativeElement, "data-gs-x", String(this.x));
renderer.setElementAttribute(nativeElement, "data-gs-y", String(this.y));
renderer.setElementAttribute(nativeElement, "data-gs-width", String(this.w));
renderer.setElementAttribute(nativeElement, "data-gs-height", String(this.h));
if(this.minWidth) {
renderer.setElementAttribute(nativeElement, "data-gs-min-width", String(this.minWidth));
}
if(cannotResize == "yes") {
renderer.setElementAttribute(nativeElement, "data-gs-no-resize", cannotResize);
}
}
}
app.component.html:
My First Grid Stack Angular 2 App
Demo
1
2
Drag me!
4
5
6
7
8
9
10
11
index.html:
Angular QuickStart
Loading...
We tried to copy the demo grid on the gridstack.js web page. If you're going to run this and you want it to look like theirs, you'll need to grab some .css files, .js files, etc. from their site.