Unable to access or modify properties within a function passed as an argument

deleteDialog(item, func: Function) {
    this.dialogService
      .open(ConfirmDialogComponent, {
        context: {
          title:"Are you sure?",
          cancelClss: "info",
          confirmClss: "danger",
        },
      })
      .onClose.subscribe((confirmed) => {
        if (confirmed) func(item);
      });
  }

The purpose of this function is to open a dialog and execute a specified function if confirmed. The goal is to dynamically pass the function to be executed upon confirmation, allowing for reusability of the dialog functionality in different contexts.
For instance, consider the following sample function:

deleteCurrencyImplementation(cur: Currency) {
 this.showSpinner = true; 
 ...
 }

While the function is getting executed and receiving the correct object as intended, modifying properties like 'showSpinner' (a public property set to true) within the function can trigger a TypeError in Angular due to it being undefined. To demonstrate how I pass the function within the HTML:

 <show-datasource 
[tableConfig]="config" [data]="currenciesFromApi"
(deleteEmitter)="deleteDialog($event, deleteCurrencyImplementation)"> 
 </show-datasource>

What could be causing this issue?

Answer №1

Connect your callback function to this. There are various ways to achieve this.

Define the function as follows:

deleteCurrencyImplementation = (cur: Currency) => {
 this.showSpinner = true; 
 ...
 }

Bind it before execution:

    .onClose.subscribe((confirmed) => {
            if (confirmed) {
               const boundFunc = func.bind(this);
               boundFunc(item);
            }
          });

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

Tips for troubleshooting Angular 4 unit testing using jasmine and karma with simulated HTTP post requests

I have a service that I need to unit test in Angular 4 using TypeScript and Jasmine. The problem is with the http where it needs to perform a post request and get an identity in return, but for some reason, no data is being sent through. My goal is to ac ...

Exploring the implementation of method decorators that instantiate objects within Typescript

Currently, I have been working on a lambda project and utilizing the lambda-api package for development. As part of this process, I have implemented decorators named Get and Post to facilitate mapping routes within the lambda api object. These decorators e ...

Is there a way to retrieve the latitude and longitude values using a plugin and then make a web service call in Ionic with Angular 5?

I am currently trying to retrieve the latitude and longitude coordinates of a location by using geocode in Angular 5 within the Ionic framework. Once I have obtained the lat long, I intend to pass it to my service. The issue I am facing is that my service ...

Received a 'Vue error: Redundant navigation to current location prevented' when attempting to refresh the page with updated parameters

I'm attempting to refresh the page with new parameters when the state changes: @Watch('workspace') onWorkspaceChanged(o: Workspace, n: Workspace){ if(o.type === n.type && o.id === n.id) return; this.$router.push({name: this.$rout ...

Add the list of information during the looping process (map)

I am currently facing a challenge where I need to update my data during the iteration and send the results to an API call. The API Call expects a request with data structured in the following format: { list: [{ id: "1", name: "Hello" ...

Using TypeScript to map over unboxed conditions: transforming OR operators into AND operators

I am working with an array that has multiple objects containing functions foo. My goal is to create a new object signature with a function foo that inherits all the signatures from the array item foo functions. let arr = [ { foo: (a: 'a') = ...

Comparing Angular 2's location.go with window.location.href

It is clear to me that location.go will alter the URL in the browser without refreshing the page, while window.location.href will reload the entire page. However, what I am uncertain about is how these methods impact SEO. The structure of my site's U ...

What is the best way to create a universal function that can return a promise while also passing along event

I created a specialized function that waits for an "EventEmitter" (although it's not completely accurate as I want to use it on other classes that have once but don't inherit from EventEmitter): export function waitEvent(emitter: { once: Function ...

Personalized angular subscription malfunction

Recently, as I dive into learning Angular 6, a question has arisen regarding the subscribe method and error handling. A typical use of the subscribe function on an observable typically appears like this: this.myService.myFunction(this.myArg).subscribe( ...

The fixed header option is not available for the CdkVirtualScrollViewport

Looking for a solution in my Angular application where I need to keep the table header at a fixed position while displaying the scrollbar only on the body part. Currently, I am utilizing the CdkVirtualScrollViewport library in Angular to render the table c ...

Having trouble with showing dynamic data in column2 of my HTML layout, and the alignment doesn't look quite right in HTML

I'm working with this HTML file, attempting to create a two-column layout using HTML and CSS. I want one column to be labeled REQUEST and the other RESPONSE. When a value is entered in the text field in Column 1, it should display a response in Column ...

Error: Unable to use 'ngForFrom' as it is not a recognized native property for binding

I have looked for solutions here and here. I am currently using angular 2 version 2.0.0-beta.7, but encountering the following error: EXCEPTION: Template parse errors: Can't bind to 'ngForFrom' since it isn't a known native property (" ...

Identifying the modifications made to a Firestore list, including additions, deletions, and changes

Utilizing Firestore as the backend has allowed me to navigate basic crud methods effectively. However, I am curious about how to identify changes within a list of returned items after the initial subscription. My goal is twofold: - Minimize the number of ...

Issue with string interpolation failing to correctly reflect the updated value from the service provider

I created a simple component to test string interpolation in HTML, <p>{{value}}</p> Here is the TypeScript file: export class HelloComponent implements OnInit { value: any; constructor(private service: ApiService) { this.value = ...

Angular Refresh Tokens

I've developed a service for calling APIs from my Angular application. Within this service, I've defined the ROOT_URL and TOKEN variables and assigned values to them. Following the declaration, there are several GET methods to access APIs using ...

Issue with material table not showing data

Problem I've been working on integrating a material design table into my project, but I'm running into an issue where the data isn't showing up. I followed the example provided here but all I see is a single vertical line on the page: https ...

Encountering an issue with Angular's <base href="/projectname/client"> directive causing an error in the index.html file

I am currently working on an Angular 7 application that is deployed on Openshift using a Docker image. I have been trying to configure the application URL to be https://ocp-1123/projectname/client, but whenever I set my base href with "/projectname/client" ...

What sets apart .to and .toService in InversifyJS?

I find the documentation on using .toService(MyClass) for transitive bindings confusing. The examples provided also show that achieving the same result is possible with a regular .to(MyClass). https://github.com/inversify/InversifyJS/blob/master/wiki/tran ...

What is the best way to display the source code of a function in TypeScript?

I am interested in obtaining the source code for my TypeScript function ** written in TypeScript **. Here is the TypeScript code: var fn = function (a:number, b:number) { return a + b; }; console.log("Code: " + fn); This code snippet displays the Ja ...

How to eliminate certain elements from the DOM in Angular 5

I'm facing a minor issue in my Angular/Typescript project that I can't seem to resolve. I am still new to these technologies and struggling with removing certain DOM elements. The content is auto-generated with specific CSS classes, and unfortuna ...