Grapesjs: Webpage plugin: import & export code options in AngularJS application

Created on 21 Jan 2020  路  10Comments  路  Source: artf/grapesjs

Hello Team,

I have bit different requirement for export and import code. Is it possible to get html and css in memory (i want to save it in DB ) instead of opening PopUp which gives an option to save zip file ?

I am using webpage plugin in angular app

Also is it possible to load page with pre-rendered or pre-supplied HTML while opening or loading container?

Requirement is to modify current behavior of export and import feature of webpage plugin

Most helpful comment

@denish-kanabar you can do this way:

editor.setComponents(
  `
     <div> Default Template! </div>
     <style> div { background: teal} </style>
  `
)

Cheers!

All 10 comments

Hi @denish-kanabar

Is it possible to get html and css in memory

editor.getHtml()
editor.getCss()

(i want to save it in DB )

please refer to the storage api

load page with pre-rendered or pre-supplied HTML

editor.setComponents('<div>Default Template!</div>')

cheers!

Hi Thanks for reply,

I tried with same code with multiple options but its giving some or other error when I try to call node API from inside command option.Below is main code of same. In the attached file same thing is in editor.component.ts and saveartifact.service.ts file
import { Component, OnInit } from '@angular/core';
import grapesjs from "grapesjs";
import { IArtifact } from '../interfaces/interface';
import { map } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { SaveartifactService } from '../services/saveartifact.service';
import * as $ from "jquery";
//import grapesjsPresetNewsletter from "grapesjs-preset-newsletter";
import gjsblock from "grapesjs-blocks-basic";
import gjswebpage from 'grapesjs-preset-webpage'
//grapesjs.plugins.add('grapesjs-preset-newsletter', grapesjsPresetNewsletter );
grapesjs.plugins.add('grapesjs-blocks-basic', gjsblock);
grapesjs.plugins.add('grapesjs-preset-webpage', gjswebpage);
declare const demo2: any;
declare const demo: any;
declare const plugin: any;
@Component({
selector: 'app-editor',
templateUrl: './editor.component.html',
styleUrls: ['./editor.component.css']
})
export class EditorComponent implements OnInit {
artifact: IArtifact = {};
constructor( private rest:SaveartifactService) { }

    // urlStore: 'http://localhost:8080/api/createArtifact',
    // urlLoad: 'http://localhost:8080/api/getAllArtifacts'

ngOnInit() {

var editor = grapesjs.init({
  container: "#gjs",
  plugins: ["grapesjs-preset-webpage", "grapesjs-blocks-basic"],
  storageManager: {
    autosave: false,
    setStepsBeforeSave: 1,
    type: 'remote',
    contentTypeJson: true,
  }
});

editor.Panels.addButton
  ('options',
    [{
      id: 'save-db',
      className: 'fa fa-floppy-o',
      command: 'save-db',
      attributes: { title: 'Save DB' }
    }]
  );

// Add the command
editor.Commands.add
  ('save-db', {
    run: function (editor, sender) {
      sender && sender.set('active'); // turn off the button
      editor.store();

      var htmldata = editor.getHtml();
      var cssdata = editor.getCss();
      console.log(htmldata);
      console.log(cssdata);

      this.artifact = {};
      this.artifact.aValue = htmldata;
      this.artifact.aVersion = 1;
      this.artifact.aCreatedBy = '[email protected]'//localStorage.getItem('emailid');
      //this.artifact.aUpdatedBy = localStorage.getItem('emailid');
      this.artifact.iterationId = localStorage.getItem('iterationid');
      this.artifact.aType = 'HTMLTemplate';
      this.artifact.aName = 'test1';
      this.artifact.projectId = '5e1d7cfa5fd91900ec3b7adb';
    this.artifact.iterationId = '5e1d7cfa5fd91900ec3b7ada';
    this.callService(this.artifact)     ;


    //http.post("http://localhost:8080/api/createArtifact", this.artifact).pipe(map(this.extractData));

      // $.post("http://localhost:8080/api/createArtifact",
      //   {
      //     //"html": htmldata,
      //     //"css": cssdata
      //     "artifact": this.artifact
      //   });

    }
  });

// editor.on('storage:load', function (e) { console.log('Loaded ', e); });
// editor.on('storage:store', function (e) { console.log('Stored ', e); });
}

callService(artifact:IArtifact){
this.rest.createArtifact(artifact).subscribe(() => {

}, (err: any) => {
  console.log(err);
});

}
studio-fabric-grapesjs-app.zip

with above attached code or snap it gives error like

ERROR TypeError: this.callService is not a function

tried with calling service function directly inside editor.command() and also tried with calling http.post of $post() but nothing worked.

Please help

@denish-kanabar unfortunetly i am not an expert on angular, have you seen this thread?
And for the code, please provide a fiddle!
cheers!

have checked that thread and from there only could import plugins but now issue is with calling API while adding command for editor to save in DB

@denish-kanabar i believe that is not a problem with grapesjs itself, you are calling a function which is not bound to this, from the code i can say that issue your post request directly in the run command and in case that is not working, please provide the error log for the failure of the post request.
cheers!

Thanks for input, below worked. It has opens sweet alert (jquery) and take that value to save in DB. Its working now.

editor.Commands.add('save-db', {
  saveToDB() {
    swal({
      title: 'Enter Page name',
      input: 'text',
      onBeforeOpen: function (ele) {
        var btnOk = $(ele).find('button.swal2-confirm.swal2-styled');
        btnOk.removeClass('swal2-confirm swal2-styled');
        btnOk.addClass('btn btn-rose btn-round');
      }
    }).then(function (val: any) {

      editor.store();  //   sender && sender.set('active'); // turn off the button     

      webpage = {};
      webpage.html = editor.getHtml();
      webpage.css = editor.getCss();

      $.ajax({
        url: endpoint,
        type: "POST",
        data: JSON.stringify(webpage),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () {
          console.log("Html and CSS saved to DB");
        }
      });
    })
  },
  run() {
    this.saveToDB();
  },
});

editor.setComponents('

Default Template!
')

thanks for this. One more question on top of this. When I click on 'View Code' option it shows html and css both. With editor.setComponents() its binding or specifying only HTML. So what about css, how do we bind css while loading existing html

I am saving both html and css in to DB , dont we need to apply both while loading also?

@denish-kanabar you can do this way:

editor.setComponents(
  `
     <div> Default Template! </div>
     <style> div { background: teal} </style>
  `
)

Cheers!

Thanks for help. It worked now used below.
editor.setComponents(this.loadSavedHTML());
editor.addComponents(this.loadSavedCSS());

First function passes HTML and other supplies CSS with

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mathiasbc picture mathiasbc  路  3Comments

faizansaiyed picture faizansaiyed  路  3Comments

kickbk picture kickbk  路  3Comments

alibouaziz picture alibouaziz  路  3Comments

tribulant picture tribulant  路  3Comments