Implementing debounce functionality in Angular using CodeMirror

I've tried various approaches and even referred to This Possible Dup

Currently utilizing the ng2-codemirror 1.1.3 library with codemirror 5.33.0 interface

Simply attempting to add a DebounceTime operator to the change event of the CodeMirror Editor

Here is the HTML snippet:

<codemirror #cm [(ngModel)]="code" [config]="config" (focus)="onFocus()" (blur)="onBlur()"></codemirror>

And here is the TypeScript code:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/debounceTime';

@ViewChild('cm') editor;

ngAfterViewInit() {
  const watch = Observable.fromEvent(this.editor, 'change'); // <--- Error
  watch.subscribe(v => console.log(v));
}

An error message displays stating:

ERROR TypeError: Invalid event target

Additionally attempted attaching the Observable.fromEvent to this.editor.value/ this.editor.input

UPDATE Complete Component: component.HTML:

<codemirror #cm [(ngModel)]="code" [config]="config" (focus)="onFocus()" (blur)="onBlur()"></codemirror>

component.TS:

import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { global } from '../shared/global.constants';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/addon/scroll/simplescrollbars';
import 'codemirror/addon/hint/javascript-hint';
import 'codemirror/addon/hint/show-hint.js';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/debounceTime';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit, AfterViewInit {
  @ViewChild('cm') editor;
  @ViewChild('output') output;
  code = global.code;
  config = {
    lineNumbers: true,
    mode: {name: 'javascript', json: true},
    tabSize: 2,
    scrollbarStyle: 'simple',
    extraKeys: {'Tab': 'autocomplete', 'Ctrl-Space': 'autocomplete'}
  };

  constructor() {

  }

  ngOnInit() {

  }

  ngAfterViewInit() {
    console.log(this.editor); // <--- CodemirrorComponent {change: EventEmitter, focus: EventEmitter, blur: EventEmitter, cursorActivity: EventEmitter, instance: CodeMirror$1, …}
    console.log(this.editor.nativeElement); // <--- undefined
    const watch = Observable.fromEvent(this.editor.host.nativeElement, 'input');
    console.log(watch);
    watch.subscribe(w => console.log(w)); // <-- invalid target
  }
}

Answer №1

When dealing with the <codemirror> component, using @ViewChild('cm') editor will query an instance of the component class. On the other hand, using

@ViewChild('cm') editor: ElementRef
may seem like a workaround for the typing system but does not actually impact the value of editor.

According to official documentation, the read property is crucial in specifying which token should be queried. To ensure that it is querying ElementRef, it needs to be written as:

@ViewChild('cm', { read: ElementRef }) editor: ElementRef;

Subsequently, an event listener can be attached to the DOM element (as elaborated in another response):

const watch = Observable.fromEvent(this.editor.nativeElement, 'change');

Answer №2

Utilize the nativeElement parameter in conjunction with the Observable.fromEvent method.

ngAfterViewInit() {
  const watcher = Observable.fromEvent(this.editor.nativeElement, 'change');
  watcher.subscribe(value => console.log(value));
}

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

Strategies for effectively conveying jQuery and Angular

I have integrated jQuery DataTable into my code. I am facing an issue with the dataTables_scrollBody class which requires me to add a custom scroll bar. This is necessary because on Linux, the touch screen functionality in Chrome is not working effectively ...

Modifying an object's label based on a particular value using JavaScript

In my current project involving React.js charts, I am looking to organize data by month. In Django, I have set up a view to display JSON containing the total events per month in the following format: [ { "month": "2022-06-01T00:00:0 ...

Guide to using jQuery to input a multi-line text into a field

Dealing with a value that spans multiple lines obtained from PHP has been challenging due to the structure of textareas. The standard method of inserting it into the textarea is not feasible in this case. I resorted to using jQuery for this purpose, but ...

What is the reason that .every() is not recognized as a function?

I have gathered a collection of required form elements and have added a 'blur' listener to them. var formInputs = $(':input').filter('[required]'); formInputs.each(function(i) { $(this).on('blur', function ...

dynamic text overlay on a bootstrap carousel

Having limited knowledge in html and css, I am using a bootstrap carousel slider with text. I am trying to change the color of the box randomly. https://i.sstatic.net/TozUP.jpg Here is the code that I am currently using: <ol class="carousel-indicato ...

The video is unavailable due to issues with ImageKit

In my project, I am incorporating ImageKit into the workflow. Currently, I have set up a basic process that only includes the video upload feature. On the backend, I have a lone file named index.js. I haven't developed a frontend yet, so I have been e ...

Stop md-select dropdown from opening when clicked in specific scenario

I currently have a situation where I want to prevent the md-select from opening under a specific condition and instead display a warning dialog. One way I can achieve this is by disabling the md-select using the following code: ng-disabled="controller.un ...

"Can you help me understand how to establish a character limit for the MUI autocomplete

Hey everyone, I have successfully created an auto-complete feature using Material UI and an API. Now, I am facing a challenge where I need to limit the suggestions returned by the autocomplete to only show matches when the user types at least 3 letters. Ca ...

Creating a JSON schema for MongoDB using a TypeScript interface: a step-by-step guide

In order to enhance the quality of our data stored in MongoDB database, we have decided to implement JSON Schema validation. Since we are using typescript in our project and have interfaces for all our collections, I am seeking an efficient method to achie ...

Using jQuery to animate a div within a PHP echo statement

<li> <a id="collection" href="collections.php"> <span class="glyphicon glyphicon-th white"> Collections</span> </a> </li> <?php include "pagination.php" ?> <script> $("#collection").clic ...

Issue with VueJS compilation: JSON data import causing failure

I'm attempting to bring in a static .json file within the <script> section of a .Vue file using the code snippet import Test from '@assets/test.json' From what I've gathered about webpack, this should work effortlessly. I have ev ...

Fulfill all of the promises within Bluebird, as well as decline any that do

I am in search of a method to retrieve both successful resolutions and rejections from a promise array. I am relying on the Bluebird implementation, so any ES6 compatible solution would be preferable. One option that comes to mind is utilizing Bluebird&ap ...

AngularJS: Using $watch to retrieve the index of the modified item within an array

My current situation involves an array containing multiple objects. $scope.userCompetences = []; To monitor any changes in this array, I have implemented a deep watch: $scope.$watch('userCompetences', function (newVal, oldValue) { ...

jQuery functions correctly within jsfiddle, yet it encounters issues when utilized within WordPress

I've been experimenting with a jQuery script to grey out the screen. While it works perfectly on my jsFiddle link provided below, I'm having trouble getting it to work from within my WordPress plugin. Check out the working script on my jsFiddle ...

Removing a function when changing screen size, specifically for responsive menus

$(document).ready(function () { // retrieve the width of the screen var screenWidth = 0; $(window).resize(function () { screenWidth = $(document).width(); // if the document's width is less than 768 pixels ...

Troubleshooting Mobile App Errors with Rails API

My mobile application is connected to a Rails server. I am encountering an issue when attempting to edit an Item in the Rails database using a JSON request from my application. The first time I make the AJAX request, I receive an error message. {"readySta ...

Swap out the content within the selected element

Let's imagine we have the following shopping list: export default { data() { return { items: { Apple, Orange, Appricot } } } } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js" ...

Convert my information to an XML document

Successfully, I have loaded the content of an XML file into my PHP document using the following method: $(document).ready(function () { $.ajax({ type: "GET", url: "abstimmer.xml", dataType: "xml", success: function ...

Leveraging the .reduce method to perform specific calculations and generate an object containing the results of an array

After successfully achieving the desired results, here is the data manipulation I have done: const days = [ { date: '2016-12-13T00:00:00.000Z', stats: [ { name: 'Soft Drinks', sold: 34, }, { name: 'Snacks&apo ...

Categorize messages based on the date they were last read in Angular

I am looking to organize my chat application messages by date, similar to the layout in Microsoft Teams app. Here is an example of the message data: [ { "id": 577, "source": { "userID": 56469, ...