How to Retrieve the Value of a Typescript Variable in a Angular 2 Component Using Javascript

I've created a reusable Angular 2 component for integrating the Summernote WYSIWYG editor into my application. This component takes in three input parameters - id, name, and body - which are then used as attributes for a rendered textarea. The issue I'm facing is that I'm initializing the Summernote plugin within the component and creating the editor. However, I want to avoid hard-coding the selector name and instead utilize the dynamic values passed as input parameters.

import {Component, ElementRef, OnInit, EventEmitter, Input, Output, Inject, ComponentRef} from '@angular/core';
import {Http} from '@angular/http';

declare var $: any;

@Component({
    selector: 'editor',
    template: '<textarea id="{{eid}}" name="{{ename}}" class="form-control">{{body}}</textarea>'
})

export class EditorComponent {

    @Input() body: string;
    @Input() eid: string;
    @Input() ename: string;
    @Output() onContentChanged: EventEmitter<any>;

    constructor(){}

    ngAfterViewInit()
    {
        $(document).on("pageLoaded", function (){
            console.log("pageLoaded");

                $("#body").summernote({
                    height: '200px',
                    callbacks: {
                        onChange: function(contents, $editable) {
                            $("#body").val(contents);
                        }
                    }
                });

        });
    }
}

In the code snippet above, you can see that I have used $("#body") twice within the ngAfterViewInit block. I am looking to replace this with the eid variable. I tried using {{eid}}, but it generated an error in the browser console:

EXCEPTION: Syntax error, unrecognized expression: #{{eid}}

Using this.eid is not valid since we're inside a JavaScript method rather than TypeScript.

This component is being used as a directive in another view file:

<editor [body]="page.body" eid="body" ename="body"></editor>

The template block of the component correctly utilizes dynamic values. The challenge lies in making the initialization fully dynamic so that it can be utilized anywhere with different IDs.

Is there a solution or approach that I might be overlooking?

P.S. Everything works smoothly at the moment. I just need to enhance the initialization process to support full dynamism, allowing it to be used across various contexts with diverse IDs.

Answer №1

If you want to maintain the context, consider using arrow functions instead of the traditional function.


$(document).on("pageLoaded", () => {
    console.log("pageLoaded");

    $(this.eid).summernote({
        height: '200px',
        callbacks: {
            onChange: (contents, $editable) => {
                $(this.eid).val(contents);
            }
        }
    });

});
}

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

Looking for tags similar to stackoverflow?

Is there a way to create a search box similar to the one in Tags where tag names are displayed immediately upon entering without pressing enter key? Could anyone provide me with a script or tutorial on how to achieve this? Is it done using JavaScript or j ...

Leveraging Javascript to identify actual text content, rather than focusing on HTML elements

Having an issue with a WYSIWYG editor (TinyMCE) saving content into the database where values are sometimes saved that contain only tags like: <p><br data-mce-bogus="1"></p> which is not actual content. My application cannot distinguis ...

How can you use Jquery's .data() method to find elements with specific values?

I have a button that generates a new drop pin. The pin is contained within a div, and a hidden form input is also created to store the position of the pin when it's dragged. In my jQuery code for creating these elements, I assign a data attribute call ...

Model data is missing from the form submission

I recently created a basic HTML POST form with a model embedded within it. Here is the link to view the demo: https://jsfiddle.net/pilotman/rn9gspz8/6/ Keep in mind that the JS fiddle example is just for demonstration purposes and may not be flawless. Af ...

Attempting to extract decibel levels from an audio file using JavaScript

I've been exploring the details provided here: Is there a way get something like decibel levels from an audio file and transform that information into a json array? However, when attempting to execute the JSBin snippet below, I encountered some conf ...

Guide to showing a preview of an image prior to submitting a form using vue.js

I created a Vue form but I'm having trouble making the image preview function work when users try to submit an image to the form. After refreshing the page, I can see the image, but when uploading it, the preview link is broken. There is an option to ...

The Kendo window does not trigger the resize event when it is restored after being minimized

According to the Telerik documentation, the Kendo window restore function should trigger a resize event. While this works as expected when the window is maximized and then restored, it does not call the resize event when the window is minimized and then ...

Vue is encountering difficulties resolving the index.vue file located in the parent directory

Having trouble importing a component from the path folder, I keep encountering an error message stating "Cannot find module './components/layout/Navbar'. Vetur(2307)". This is how I am attempting to import the component: import Navbar from "./c ...

Unveiling the mystery: Locating the position of an element within a multidimensional array using JavaScript or JQuery

How can I retrieve the index of a specific element in a JSON array converted from a PHP array using json_encode, using JavaScript or JQuery? Initially, the user will choose an option where the values correspond to people's IDs. <select class="for ...

Optimizing React components by efficiently updating props without triggering unnecessary renders

As I delve into learning React, I've encountered a challenge with using a component to display details of a selected item in a table. The issue arises when clicking "Next" on the paginated table, causing the state to update and re-render the component ...

Unlocking the Power of React: Leveraging Component Functions Through Click Events on vis.js Edges

I'm working on a React component that looks like this: export default class App extends Component { // ... _openDialog = () => { this.setState({ isDialogOpen: true }); }; render() { return ( <div> <div clas ...

Checking the alignment of a label or element in the center of a webpage using javascript

I am new to JavaScript and was attempting to determine if an element is centered aligned by accessing its CSS properties/values. Can someone help me retrieve the CSS property to verify text alignment using JavaScript? ...

Steps to converting an enum or literal

Hey there, I'm relatively new to working with TypeScript and I've been experimenting with transforming enums/literals using functions. For instance, creating a capitalize function that capitalizes the first letter of a string. (e.g., mapping typ ...

Switching to http2 with create-react-app: step-by-step guide

Can someone provide guidance on implementing http2 in the 'create-react-app' development environment? I've searched through the README and did a quick Google search but couldn't find any information. Your assistance is much appreciated. ...

A Guide to Implementing Inner CSS in Angular

I am working with an object named "Content" that has two properties: Content:{ html:string; css:string } My task is to render a div based on this object. I can easily render the html using the following code: <div [innnerHtml]="Content.html"& ...

Converting Typescript fat arrow syntax to regular Javascript syntax

I recently started learning typescript and I'm having trouble understanding the => arrow function. Could someone clarify the meaning of this JavaScript code snippet for me: this.dropDownFilter = values => values.filter(option => option.value ...

What is the best way to send multiple parameters to @Directives or @Components in Angular using TypeScript?

I am facing some confusion after creating @Directive as SelectableDirective. Specifically, I am unclear on how to pass multiple values to the custom directive. Despite my extensive search efforts, I have been unable to find a suitable solution using Angula ...

Return to Angular 7 instead

Is there a way to revert back to angular 7 from angular 8? I had saved a branch in angular 7, but once I did npm install on the angular 8 branch, I started getting a plethora of errors with every build. Even after trying npm install again on the angular ...

What is the best way to visually refresh a polymer element that displays data from a frequently changing URL?

Hey there! I'm currently facing an issue with displaying a polymer element that contains some important information. This element is supposed to appear when I tap on an icon, but for some reason it doesn't show up even after the data has been loa ...

Understanding the meaning of `.then()` in Excel JavaScript involves recognizing its function

Excel.run(function (context) { var sheet = context.workbook.worksheets.getItem("Sample"); var range = sheet.getRange("B2:C5"); range.load("address"); return context.sync() .then(function () { ...