Utilizing a wysiwyg text editor in conjunction with Angular 2

I am currently implementing a wysiwyg feature in my Angular2 project. When I include the code in the index.html page (the root page), it functions correctly.

However, when I try to use it in a child view HTML file, the CSS and JavaScript do not load properly, resulting in the wysiwyg editor not displaying as expected.

<!doctype>
<html>
<head>
    <base href="/">
    <title>Arkloud Adservio</title>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0"/>
    <!-- Load libraries -->
    <!-- IE required polyfills, in this exact order -->
    ...

In the scenario where I place the wysiwyg editor in my index.html, everything works perfectly.

However, if I attempt to move this functionality into another view component, it fails to function properly.

<div id="editor">
        <form>
          <textarea id='edit' style="margin-top: 30px;" placeholder="Type some text">
            <h1>Textarea</h1>
            <p>The editor can also be initialized on a textarea.</p>
          </textarea>

            <input type="submit">
        </form>
    </div>

Answer №1

My recommendation aligns with @mayur's suggestion to utilize angular2 in combination with tinyMCE. If you require further instructions on the implementation, following the guidance provided by @mayur:

For the TinyMCE directive located at directives/tiny.directive.ts:

import {Directive} from '@angular/core';
declare var tinymce: any;
// Custom directive for TinyMCE
@Directive({
    inputs: ['htmlEditor'],
    selector: '[htmlEditor]'
    })
export class EditorDirective{
    constructor(){
        tinymce.init({
            selector: 'textarea', //modify this to target a specific class or id
            schema: 'html5',
        });
    }
}

In app.component.ts:

import { Component } from '@angular/core';
import {EditorDirective} from './directives/tiny.directive';

@Component({
    selector: 'my-app',
    directives: [EditorDirective],
    templateUrl: '<textarea [htmlEditor]></textarea>'    //Using [htmlEditor]="Form.find('Text')" resulted in an error in my case, so proceed with caution
    })
export class AppComponent {

}

Within main.ts:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent  } from './app.component';
bootstrap(AppComponent);

In index.html:

<html>
<head>
    <!--include title/metadata etc. here-->

    <!-- 1. Load libraries -->
    <!--
    include libraries here
    refer to the Angular2 quickstart guide for assistance
    importing jQuery may be necessary for Tinymce
    -->
    <script src="//cdn.tinymce.com/4/tinymce.min.js"></script>

    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
        System.import('app').catch(function(err) {
            console.error(err);
        });

    </script>
    <!--remember to include styles!-->
</head>
<body>
    <div>
        <my-app>Loading...</my-app>
    </div>
</body>

I hope this information proves helpful.

Answer №2

If using react with Summernote .. Why summernote?

 //.js
import {EditorComponent} from '/../components';
@Component({
    selector: 'Bar',
    components: [EditorComponent],
    template: '<div [textEditor]="Form.find('Content')"></div>'
})

// Summernote component 
@Directive({
    inputs: ['textEditor'],
    selector: '[textEditor]'
})

summernote.init({
    selector: '.summernote-editor',
    schema: 'html5',
});

Homepage.html

<script src="//cdn.summernote.js/tinymce.min.js"></script>
<script src="browserify.config.js"></script>
<script>
System.import('main').catch(function(err) {
    console.error(err);
});
</script>

For more information visit Summernote

Answer №3

Here are detailed instructions on how to set up TinyMCE in your Angular application:

  1. To begin, install TinyMCE using the following npm command:

    npm install --save tinymce
    
  2. In your file, specify the path for the TinyMCE script files as shown below:

    "scripts": [
        "../node_modules/tinymce/tinymce.js",
        "../node_modules/tinymce/themes/modern/theme.js",
        "../node_modules/tinymce/plugins/link/plugin.js",
        "../node_modules/tinymce/plugins/paste/plugin.js",
        "../node_modules/tinymce/plugins/table/plugin.js"
     ],
    
  3. Run the provided command to copy the styles into the assets folder:

    xcopy /I /E node_modules\tinymce\skins src\assets\skins
    
  4. Create a directive for TinyMCE to use it throughout your application:

     // Include necessary imports
    
    // Define SimpleTinyMceDirective class
    
    // Initialize and configure TinyMCE instance
    
    // Export the directive 
    

    Save this directive as simple-tinymce.directive.ts

  5. Now, within the app.module.ts file, include the following imports:

    import * as tinymce from 'tinymce';
    import {SimpleTinyMceDirective} from './common/simple-tinymce/simple-tinymce.directive';
    
  6. You can now include the TinyMCE editor in your component template like so:

    <textarea id="description" class="form-control" name="description" placeholder="Enter the description" required [(ngModel)]='description' #description='ngModel' 
        (htmlEditorKeyUp)="onHtmlEditorKeyUp($event)" htmlEditor></textarea>
    
  7. To access the content in your component.ts file, use the following function:

    onHtmlEditorKeyUp(content:any):void{
        console.log(content);
    }
    

Answer №4

Despite following the provided answers, I faced difficulty getting this feature to work properly. This could be attributed to the fact that I am using routing and the DOM element where the directive should be applied is not yet available. To resolve this issue, I simply transferred the tinymce.init code from the constructor to the ngOnInit function, resulting in successful execution:

Here is the revised code for directives/tiny.directive.ts:

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

// Tinymce directive
@Directive({
    inputs: ['htmlEditor'],
    selector: '[htmlEditor]'
})
export class EditorDirective implements OnInit {
    
    ngOnInit(){
        tinymce.init({
            selector: 'textarea', //modify this based on a specific class/id
            schema: 'html5',
        });
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is it that after running "ng build" with Angular CLI, the project does not function properly?

(Greetings fellow Earthlings, I come in peace from the distant planet Angular2 (formerly known as Flex/Actionscript). Please pardon my ignorance with this question) Am I mistaken to assume that by running the "ng build" command on my project using Angular ...

single-spa: revolutionizing console.log for each microfrontEnd

Imagine having multiple single-spa react microfrontend apps in your project, such as Cart and Products The goal is to modify console.log, console.error, etc. so that they include a prefix indicating the corresponding microfrontend app: console.log call ...

The intersectObjects function is failing to retrieve the object from the OBJMTLLoader

Within my scene, I've introduced a new object along with several other cubes. To detect collisions, I'm utilizing the following code snippet that fires a Ray: var ray = new THREE.Raycaster(camera.position, vec); var intersects = ray.intersectObj ...

Issue with Firestore rule functionality not meeting expectations

I have set up the following rule on Firestore: service cloud.firestore { match /databases/{database}/documents { match /items/{itemid} { allow read, write: if request.auth.uid == resource.data.owner; } } } When initializing my collec ...

Tips for creating an HTML table that fills the entire width of its parent element:

One of the rows in my table contains a nested table. I want both tables to fill up 100% of the width of the parent element. How can I achieve this? Check out the demo here Here's the HTML code: <div class="container"> <table> <tr ...

Retrieve data from an AJAX call and PHP script upon successful completion

Utilizing AJAX (jQuery), my aim is to submit a form to user-ajax.php and expect the page to echo back a response like "success". In my AJAX code, I am checking the response value for success but it's not working as expected. Below is the PHP code snip ...

Using AngularJS routing with an Express 4.0 backend API

Recently, I began working on an application utilizing Express 4.0 server. Following a tutorial on scotch.io (http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4), I structured the routes to support a backend api serving an An ...

Enhancing HTML Documents with the Header Element

When HTML 5 was implemented, it brought along new semantic tags such as header and footer. I find myself puzzled on whether I should use the header tag directly or assign a class of "header". Which option is superior and why? ...

Ways to increase the font size of input text using bootstrap's css framework

I currently have a bootstrap textbox set up like this: <input type="text" class="span9" required name="input_text"/> My goal is to increase the height of my input box to 300px. The width, on the other hand, is being handled by span9. I utilized In ...

Element with absolute positioning inside a relative parent does not interfere with other elements outside of the parent

I am currently facing a challenge with a simple dialog that is positioned absolutely in the center of the screen. Inside this dialog, there is a dropdown with a relatively positioned parent (I want the dropdown to follow its parent's position without ...

The issue of Elasticsearch results not being correctly parsed as JSON objects by JavaScript when retrieved from a Python client

I am facing an issue with extracting a Javascript object from the Elasticsearch(2.1.1) response received through my Python (2.7) client. Python code: es=Elasticsearch(); @app.route('/output') def findSpots(): lat = request.args.get('la ...

Node JS excels in its ability to handle non-blocking operations

In my database query method, I created a function called getParam(). Here is how it looks: function getParam(tableName, paramName, id){ var param=0; var query = client.query('SELECT '+ paramName + ' AS myparam FROM ' + tableName + &ap ...

When using RS256 with JWT, the private key will not be accepted

I've been attempting to generate a JWT using 'jsonwebtoken' with RS256. The keys were generated using the following command: ssh-keygen -t rsa -b 4096 -m PEM -f <filename> The private key output appears as follows: -----BEGIN RSA PRIV ...

Discover the Maximum Total that is Below or Equal to a Specified Limit

Here is a function I am working with: var data = [12,23,14,35,24]; //debugger; function findMaxSum(dataArr, targetSum){ var currentSum = dataArr[0]; var maxSum = 0; var start = 0; for (var index = 1; index < dataArr.length; index++) { whi ...

Explore button that gradually decreases max-height

I have a "Show More" button that expands a div by removing the css attribute max-height, but I want to add an animation similar to jQuery's slideToggle() function to smoothly reveal the rest of the content. This is the code I am using: <div id="P ...

Waiting for a function to complete its processing loop in Angular 7

In my code, I'm dealing with an angular entity called Z which has a property that is a list of another entity named Y. My goal is to delete the entity Z, but before doing so, I need to also delete all the Y entities within it. The challenge arises fro ...

Omit certain components from the JQuery ListNav plugin

I recently incorporated the Jquery plugin for record filtration. I obtained this plugin from the following link: After successfully implementing the plugin, I encountered an issue where it was counting the headings along with the alphabet filters in my co ...

Error TS2322: The variable is of type 'BillingSummaryDTO[]' and cannot be assigned to type 'never'

I've been working on a Recharts chart and I'm trying to populate it with data from an API call. Here's my current approach: export default function Billing() { const [chartData, setChartData] = useState([]); const [isLoading, setIsLoadin ...

External vendor scripts such as JavaScript and jQuery are not functioning properly after being rendered in a ReactJS environment

I am currently developing a frontend web app using ReactJS. I obtained a template from W3layout that is built with HTML5, CSS3, and custom JS files, along with various third-party/vendor plugins like nice-select, bootstrap, slik, owl-carousel, etc. Despit ...

Selenium and PhantomJS are having trouble interpreting JavaScript code

Currently experimenting with Selenium and PhantomJS for Java search tasks, I'm facing an issue where PhantomJS fails to activate javascript. My goal is to access a webpage that utilizes javascript. Previously, this method worked well for me, but now I ...