Search code examples
angularckeditor4.x

How to encode the HTML input in ckeditor in angular


I am using ng2-ckeditor in my angular project i need to encode the < and > as &lt ,&gt ,so how to encode the input HTML

.html                                                                                                       
<ckeditor> </ckeditor>
<button type="button" (click) ="submit()">Click Me!</button>   

.ts

import { Component, OnInit } from '@angular/core';
declare var CKEDITOR: any;

@Component({
  selector: 'app-html-editor',
  templateUrl: './html-editor.component.html',
  styleUrls: ['./html-editor.component.css']
})


export class HtmlEditorComponent implements OnInit {
  constructor() {
  }
  ngOnInit() {


  }

  submit() {
    var editor = CKEDITOR.instances.editor1;
    var data = editor.getData();
    console.log(data)
  }
}

Solution

  • You can convert whatever character you want. Below is code that will take str as input and return converted string.

    function convertHTML(str) {
        // &colon;&rpar;
        var Regcheck = /\W\s/gi;
        var htmlListObj = {'&':"&amp;",
                          "<":"&lt;",
                          ">":"&gt;",
                          '"':"&quot;",
                          "'":"&apos;"};
        var a = str.split("");
        var b =[];
    
        for (var i in a) {
             if (htmlListObj.hasOwnProperty(a[i])) {
                 b.push( htmlListObj[a[i]]);
             }else{
                 b.push(a[i]);
             } 
        }
        var c = b.join("");
       return c;
    }