Execute a function in Angular 9 whenever a variable undergoes a change in value

There are numerous versions of this question, many containing excessive and irrelevant details. Take into consideration the following scenario in a globals.ts file

interestingString:string = 'blah';

now in a neighboring component neighbor.ts file

displayMsg:string = this.formatInterestingStrs(this.globals.interestingString);

formatInterestingStrs(val:string) {
     return val.substr(0, 21) + "...";
}

and in the HTML...

<div> here's the first 21 characters of something intriguing: {{displayMsg}} </div>

lastly... any other component can change the string at any point in time...

this.globals.interestingString = "I saw Cher in real life today! Man, did she dish on Greg Allman!"

I COULD address this by coding the HTML like so...

<div> here's the first 21 characters of something interesting: {{this.formatInterestingStrs(this.globals.interestingString)}} </div>

...however, this impacts performance. What I would prefer is to be able to "easily" make the globals variable observable or published when modified AND have every instance of it subscribe to the changes and THEN invoke a function to handle any additional alterations that rely on its value. Something equivalent in the globals...

PublishUpdates(interestingString:string = 'blah');

and in the module...

SubscribeToUpdates(this.globals.interestingString).thenDoThis(result){
     this.displayMsg = this.formatInterestingStrs(result);
}

...and I'd like to achieve this without adding excessive bulk or numerous extra lines of code and procedures. Any suggestions?

Answer №1

After dedicating the entire day to research, I have discovered a solution to your query. The best approach is to utilize multicast observables from RxJS in your Angular application for optimized efficiency.

To implement this, simply add the following code snippet to your globals.ts file...

import { Observable, Subject } from 'rxjs';

  public interestingString:string = 'blah';

  public updateString$ = Observable.create((observer) => {
    observer.next(this.interestingString);
  });

  public interestingString$ = new Subject();

Next, incorporate the following code snippet into as many component .ts files as needed...

ngOnInit(): void {

    this.globals.interestingString$.subscribe((data) => {
      console.log('interestingString$: ' + data);
      //perform desired actions upon change of interestingString
    });
    //...add any additional code here
}

For the final step, whether within this module or another, trigger an event (e.g., click on a button) to simultaneously update all subscribers with the new value...

this.globals.interestingString = "I saw Cher in real life today! Man, did she dish on Greg Allman!";
//updateProfile will automatically .next the current profile
// ...and then will push to all subscribers of profile$
this.globals.updateString$.subscribe(this.globals.interestingString$);

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

Alter the button's operation when clicked

I am looking for some guidance on my project. I have a button in my application that allows users to add a movie to their watchlist. My goal is to change the functionality of this button to "remove from watchlist" when it is pressed. How can I achieve this ...

Issue TS7053 occurs when trying to access any index of the target of a React.FormEvent<HTMLFormElement>

I've been working on adapting this tutorial to React and TypeScript. Here is the code snippet I have implemented for handling the onSubmit event: const handleSignUp = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); ...

Tips on utilising the datepicker solely with the calendar icon, avoiding the need for any input fields

I'm currently working on a Datatable filter and I would like to incorporate a calendar icon to facilitate date filtering by simply clicking on the Datatable Header. At this stage, I've managed to display a calendar Icon on my Datatable header, b ...

Having trouble connecting to remote databases such as Supabase, MongoDB Atlas, or Neon DB using the Prisma ORM

I've encountered the same issue across all my projects. Everything runs smoothly when I work with local databases like postgres or mongodb (within a docker container on my machine). However, connecting to remote databases such as mongo db atlas, supab ...

What is the best way to convert this object/array into TypeScript?

My React application contains a data structure organized in the following format: data = { 2021-03-01: { "date": 1st March, "value": 17 }, 20 ...

A guide on combining [(ngModel)] and innerHTML in an Angular div with the contenteditable attribute

Check out this snippet of code: <div #editor class="editor" style=" max-height: 200px;" (input)="onChange()" [(ngModel)]="blogData.description" name="description" contenteditable& ...

Is there a way to create a universal getter/setter for TypeScript classes?

One feature I understand is setting getters and setters for individual properties. export class Person { private _name: string; set name(value) { this._name = value; } get name() { return this._name; } } Is there a w ...

What is the best approach for defining variables in typescript?

Let's talk about creating a variable for a car: export class ICar { wheels: number; color: string; type: string; } So, which way is better to create the variable? Option one: const car = { wheels: 4, color: 'red', type: &apos ...

Tips on utilizing JavaScript to retrieve all HTML elements that have text within them, then eliminating the designated element and its descendants

Simply put, I am looking to extract all the text-containing elements from the HTML and exclude specific elements like 'pre' or 'script' tags along with their children. I came across information suggesting that querySelectorAll is n ...

Angular2 encounters an error when processing a custom HTTP request

I offer two unique services Custom HTTP client service fetch(url):any{ this.storage.fetchData('auth-token').then((token) => { let headers = new Headers(); this.prepareHeaders(headers); return this.http.fetch(url+"?token="+toke ...

Slideshow through each item using Typescript and Angular8

I came across a solution in this carousel on by one link, but I'm struggling to work with the jQuery code even though I have JQuery installed in my project. For example: const next = jQuery(this).next(); I am looking to convert the JQuery code from ...

Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so: function MyDirective(): ng.IDirective { var directive = <ng.IDirective>{ restrict: "E", template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGrid ...

Place an image at the top of the canvas at a specific location

Currently, I am in the process of reconstructing this specific website My approach involves working with React (similar to the aforementioned site) and utilizing the same cropper tool that they have implemented. For cropping, I am incorporating react-imag ...

Tips on converting Nextjs generated Prisma types case from snake_case to camelCase

I have a full-stack application built with Next.js and Prisma ORM "next": "12.3.0" "prisma": "^4.5.0" Essentially, I am looking to convert the case of my types from snake_case to camelCase to align with the front-en ...

Is it possible to specify the timing for executing Typescript decorators?

One issue I've encountered is that when I define a parameterized decorator for a method, the decorator runs before the method itself. Ideally, I'd like the decorator to run after the method has been called. function fooDecorator(value: boolean) ...

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

Typescript: utilizing self-referencing static properties in classes

There is a blog post discussing the Github issue related to Polymorphic this within static methods. Additionally, there is a question thread on Stack Overflow that addresses this topic here. These resources explore potential solutions and workarounds for h ...

What is preventing TypeScript from identifying the type of a parent based on its child?

Take a moment to explore the following example: type Num = { type: 'NUMBER' numberValue: number } type Str = { type: 'STRING', stringValue: string } type B_Num = { a: Num; numberData: number; } type B_Str = { ...

What is the proper way to specifically define a new property on the `global` object in TypeScript?

I want to define a type signature for the variable below: (global as any).State = { variables: {}, }; How can I declare the type of State? If I try (global as any).State: Something = ..., the compiler displays an error message saying ; expected. It se ...

Utilizing an Android .arr file in a Nativescript application

Our team has successfully developed an AAR file that functions as a native Android application for reading cards and returning card details in JSON format asynchronously. After importing this AAR file into our NativeScript project, we are now exploring h ...