The defaultValue of the Observable TextArea is blank space following the transmission of a sendMessage using SignalR in a Typescript

i am currently in the process of modifying a basic SignalR Chat feature.

Here is the situation: when a user sends a message, the message gets sent successfully. However, the textarea from which it was sent remains filled with empty space (aside from the placeholder). This space consists of about 13 white spaces stored in event.currentTarget.defaultValue. I have attempted to resolve this by setting it to null or '', but the whitespace persists and obscures the placeholder.

The original input field is a string, but in my version, I have converted it into a BehaviorSubject. Additionally, I have added an observable of that BehaviorSubject.

txtMessage: string = null; 
txtSubject: BehaviorSubject<string>;
txtStatus: Observable<string>;
this.txtSubject = new BehaviorSubject<string>(this.txtMessage);
this.txtStatus = this.txtSubject.asObservable();
this.txtStatus.subscribe(status => {
  if(status !== null && status.length)
    let senderid = this.userid;
    let receiverid = this.selectedChatFriend.id;
    let message = 'typing:' + senderid + ';receiver' + receiverid;
    this.chatService.startedTyping(message);
  }
  if(status == null  && this._selectedChatFriend !== null && this._selectedChatFriend !== undefined){
    let senderid = this.userid;
    let receiverid = this.selectedChatFriend.id;
    let message = 'nottyping:' + senderid + ';receiver' + receiverid;
    this.chatService.stoppedTyping(message);
  }      
}); 

Issue at hand: After a user sends a message, the recipient is notified. Initially, everything works smoothly on the first message. However, subsequent messages show the whitespace instead of resetting to an empty textarea with a null value. As a result, the isTyping event is not triggered when the user starts typing again due to the if statement in 'starttyping' not anticipating whitespace.

textinputreceived(event: any){      
  if (event.currentTarget.value.length > 0 && event.inputType == "insertLineBreak"){      
  //event.preventDefault();
  this.sendTextMessage(event.currentTarget.value); 
  }
 
  //filter out anything that is not the txtMessage
  if(event.currentTarget.value.length == 1  && event.inputType == "insertText"){
  //user started typing     
  //triggers the isTyping
  this.txtSubject.next(event.data);    
  
  } else if (event.currentTarget.value == '' && event.inputType == "deleteContentBackward"){
  //user just deleted the only char in the message
  //triggers stopped typing
  this.txtSubject.next(null);
  }      
}

The HTML:

<div class="type_msg">  
        <div class="input_msg_write">  
          <textarea type="text"  
                    id="chatbx"                     
                    placeholder="Type a message"
                    class="write_msg" 
                    [value]="txtMessage"                            
                    (input)="textinputreceived($event)"      
                    (keydown.enter)="sendTextMessage($event)">
          </textarea>  
          <button class="msg_send_btn" 
                  type="button"  
                  (click)="sendTextMessage($event)">
                  <i class="fa fa-paper-plane-o" aria-hidden="true"gt;
                    <mat-icon style="color:black;margin-top:10px; font-size: 42px; margin-left: -45px;">send</mat-icon>
                  </i>
          </button>  
        </div>  
      </div>  

and the method to send messages:

sendTextMessage(event: any): void {
this.message = new ChatMessage();    
if (this.selectedChatFriend) {
  this.message.messageReceiverId = this.selectedChatFriend.id;
}   
this.message.message = event.currentTarget.value;  
this.txtSubject.next(null);
event.currentTarget.value = null;  
this.txtMessage = null; 
this.message.messageSenderId = this.userid; 
this.message.type = "sent";  
this.message.timeStamp = new Date();      

if(this.message.messageReceiverId && this.message.message.length > 0){
  debugger; //hier pauze is al genoeg  om te werken :o      
  } 
this.chatService.sendMessage(this.message);    
} 

There are a few peculiar occurrences:

A. It takes only one backspace press to delete the whitespace (13 characters), reveal the placeholder, and trigger the isTyping event. I tried simulating a JQueryEvent keypress for backspace without success.

B. When I debug the sendmessage function line by line in the browser's debug mode, everything functions as intended. However, under normal conditions, some issues arise. I experimented with delays and code reorganization but did not achieve the desired outcome.

C. In my chat.html file, where users input their messages, I have two methods specified: (input)="textinputreceived($event)" and (keydown.enter)="sendTextMessage($event)". If I remove the latter, the condition "event.currentTarget.value.length > 0 && event.inputType == "insertLineBreak"" does not activate upon the first Enter key press—only after pressing backspace, does it become active (likely due to the initial whitespace defaultValue). Yet, removing this leads to other complications.

I am still grasping TypeScript concepts and may be overlooking something fundamental (I read about thread-related issues). If you have any suggestions on how to tackle this challenge, I would appreciate your insights!

Additional attempts I made:

- Manipulated the value bindings using [] and [()];

- Attempted changing the textarea to a div, but no success;

Update: After delving deeper and condensing everything into a single line, I managed to reduce the whitespaces to only one character. I also tried manipulating the DOM to eliminate it, but so far, no luck. The strangest part is that this solution works fine when I debug step by step...

Answer №1

Discovered the issue at hand! In both cases, when (input)="textinputreceived($event)" and (keydown.enter)="sendTextMessage($event)", they trigger an 'enter press'. In debug mode, the enterpress event is registered, text is cleared, and message is sent. However, outside of debug mode, the enterpress event is likely registered after the field has been cleared, leading to the whitespace.

An easy fix: Use event.preventDefault() in both methods!

textinputreceived(event: any){      
if (event.inputType == "insertLineBreak"){      
event.preventDefault();    
}


sendTextMessage(event: any): void {
event.preventDefault();
//rest of logic
}

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

Angular: Is it possible to gather data from multiple observables and store it in a regular array?

I am facing a challenge where I need to retrieve data from the backend and pass it on to a child component. Here is what I have so far: ... @Component({ selector: 'my-component', template: `<my-child-component [data]="data">& ...

Looking to incorporate ipcRenderer from Electron into your Angular project? Having trouble accessing variables passed from the preload script?

I am struggling with incorporating ipcRenderer into the 'frontend' code of my electron app. Although I found examples in the documentation that use require, this method is not accessible on the frontend side where I am utilizing Angular. In the ...

TypeScript enables the use of optional arguments through method overloading

Within my class, I have defined a method like so: lock(key: string, opts: any, cb?: LMClientLockCallBack): void; When a user calls it with all arguments: lock('foo', null, (err,val) => { }); The typings are correct. However, if they skip ...

You can easily search and select multiple items from a list using checkboxes with Angular and TypeScript's mat elements

I am in need of a specific feature: An input box for text entry along with a multi-select option using checkboxes all in one place. Unfortunately, I have been unable to find any references or resources for implementing these options using the Angular Mat ...

Unlocking the potential: passing designated text values with Javascript

In my current React code, I am retrieving the value from cookies like this: initialTrafficSource: Cookies.get("initialTrafficSource") || null, Mapping for API const body = {Source: formValue.initialTrafficSource} Desired Output: utmcsr=(direct)|utmcmd=(n ...

Using the `require('ts-node/register')` method for programmatic implementation in TypeScript

ts-node recommends using require('ts-node/register'). This is also evident in the angular2-webpack-starter Protractor configuration. What exactly does require('ts-node/register') do? Does it modify require to compile TS files, allowing ...

Having difficulty using the Angular 6 "generic type elementref requires 2 type arguments" error message in my code

When attempting to use ElementRef, I included the following import statement: import { Component, OnInit, ElementRef, ViewChild } from '@angular/core'; I followed the examples and injected it into the constructor as shown: constructor(private ...

HTTP request returns a status code of 200 without any accompanying response data

Attempting to send an http request upon a page refresh in my Angular frontend to a nodejs backend, expecting to receive a token as a response. However, sometimes the request gets cancelled and even when it is successful (status code 200), the token is not ...

The appendComponentToBody function seems to be malfunctioning within Angular 2

I'm having trouble with the appendComponentToBody function in my code. I can't seem to figure out where I went wrong. Can someone please assist me in resolving this issue? Here is a link to see my code: https://stackblitz.com/edit/angular-axhgid ...

I'm trying to convert the object values into an Array in Angular 8 - any suggestions on how to

I have a set of object values that I need to convert into an array format. var data =[ { "project": "Sciera Internal Application", "hours": { "DATA SCIENCE": 3270, "DEVELOPMENT": 2895 ...

Customize Colors to Match Background in SASS

I want to design a dynamic tag component in Angular, where users can input a background color and have the font color automatically adjusted to either light or dark based on the specified color. Here's how my component is structured: <span class=& ...

Testing Angular combineLatest with Jest

I'm encountering a challenge in an assessment involving a complex Statement related to combineLatest. Here is the snippet of code: component: export class ErinnerungenErinnerungenComponent implements OnInit, OnDestroy { ... erinnerungen: Erinne ...

Using the useEffect hook with Redux-Toolkit dispatch causes an endless cycle of execution

Issue I am encountering an infinite loop problem when using useMutation from react-query to make post requests, retrieve user information from JSON, and then store it in my redux store using useEffect based on the status provided by the useMutation hook. ...

What is the process for configuring React on one server and springboot on a separate server?

Can you help me with the setup of the following: Web Server : I need to set up a react + typescript application using npm at Backend Server : I also need to configure a Springboot backend server at I am currently using webpack to build the react applica ...

What is the best way to bring in this interface from the React-Particles-JS library?

I have been attempting to segregate my parameters from my JSX within the react-particles-js library. I organize my parameters in an Object: let config = { "particles": { "number": { "value": 50 }, ...

Converting Typescript Object Types to Array Types with Tuple Structures

Presently, I have the following: interface Obj { foo: string, bar: number, baz: boolean } The desired outcome is to convert this interface into the tuple format below: [string, number, boolean] Is there a way to achieve this conversion? Up ...

Guide to adding an external script file to an Angular component

Incorporating an external api into my angular project has presented some challenges. In a normal HTML/Javascript setup, all that is required is: <script src="http://api.eventful.com/js/api"></script> <script> EVDB.API.call("/events/get" ...

Incorporating a component specified in a .jsx file into a TypeScript file

We recently acquired a react theme for our web application, but ran into issues transpiling the components. After resolving that problem, we are now facing type-related challenges. It seems that TypeScript is struggling because the props do not have a def ...

Navigating through Expo with Router v3 tabs, incorporating stack navigation, search functionality, and showcasing prominent titles

I've been working on designing a navigation header similar to the Apple Contacts app, with a large title and search function, but only for the Home Screen. All other tabs should have their own unique settings, like different titles or hidden navigatio ...

extract the text content from an object

I am trying to add an object to the shopping cart. The item contains a key/value pair as shown in the following image: https://i.stack.imgur.com/5inwR.png Instead of adding the title with its innerText using p and style, I would like to find another ...