When a function is transferred from a parent component to a child component's Input() property, losing context is a common issue

I have encountered an issue while passing a function from the parent component to the child component's Input() property.

The problem arises when the parent's function is called within the child component, causing the this keyword to refer to the child component's context instead of the parent component's context.

Below is an example implementation in the parent component:

export class CustomerComponent implements OnInit {
    next(continuationToken: string): Observable<CustomerSearchResult> {
        console.log('invoked');
        return this.customerService.searchCustomersPaged("andrew");
    }
}

In the parent component's template (passing the 'next' function as 'nextDelegate' input parameter):

<app-datatable [hidden]="!customersByFirstNameHasResults" [nextDelegate]="next" [serverSidePaging]="true" id="customersByFirstName" [showDeleteButton]="false" [showEditButton]="true" [responseModelObservable]="customersByFirstName"
      modelTypeName="customer" (editRow)="editCustomer($event)">
    </app-datatable>

When attempting to invoke the method passed in within the child component, the context is incorrect.

export class DatatableComponent implements AfterViewInit, OnDestroy, OnInit {
  @Input() nextDelegate: (continuationToken: string) => Observable<CustomerSearchResult>;

private initializeDtOptions() {
// Storing current class reference in a variable to use it in jQuery 

// Function because we can't 
    // Use arrow function as we might need both 'this' references
    if (this.serverSidePaging) {
      this.dtOptions = {
        pagingType: 'simple',
        serverSide: true,
        processing: true,
        pageLength: 10,
        deferLoading: 100, //this.totalRecords
        ajax: (p, callback) => {
          // Called here
          that.nextDelegate("").subscribe(x => {
            callback({

            })
          });

        }
      };
    } else {
      this.dtOptions = {
        pagingType: 'full_numbers',
        columns: this.columnSettings
      };
    }
  }
}

Answer №1

when you mention context, I believe you are referring to scope. This assumption is incorrect due to the way your function has been defined.

Consider utilizing:

export class CustomerComponent implements OnInit {
    public next = (continuationToken: string): Observable<CustomerSearchResult> => {
        console.log('invoked');
        return this.customerService.searchCustomersPaged("andrew");
    }
}

However, it appears that there may be room for improvement. I recommend utilizing outputs or injecting a service to manage this scenario.

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

Adjusting the height of an Angular CDK virtual scroll viewport based on dynamic needs

Currently, I am developing an Angular table with the cdk Virtual Scroll feature. Is there a method to adjust the scroll viewport's height dynamically? While the standard style property works, I am encountering difficulties setting the value using ngSt ...

Picture disappearing following the refresh of an AJAX iframe

Currently, I am developing a profile system where the user's profile is displayed in an iframe that reloads when the form submit button is clicked. The content updates successfully upon reloading, but there is an issue with images not displaying after ...

When making an Axios API request in Next.js, an error is encountered stating that the property 'map' cannot be read as it is undefined

Hey there! I've been trying to fetch data from the API endpoint in my NextJs application using axios. However, whenever I try to map over the retrieved data, NextJs keeps throwing the error message "TypeError: Cannot read property 'map' of ...

Exploring the capabilities of ExcelJS for reading xlsx files within an Angular environment

I'm trying to access a source file, make some changes to it, and then provide it for the user to download. However, I am facing an issue with reading the source file from my project directory. Below is my implementation using excelJS for file reading: ...

The value of the filename property cannot be determined as it is undefined

Hey everyone, I'm currently working on a project using nestjs and reactjs. I encountered an error when trying to add a document that reads: "Cannot read properties of undefined (reading 'filename') in multer.config.ts" import { diskStorag ...

JavaScript News Scroller for Horizontal Display

After searching through numerous websites, I have yet to find the ideal horizontal news scroller for my website. My specific requirements include: Must provide a smooth scrolling experience Scroll from right to left covering 100% width of the browser ...

Leveraging Parameters in Ajax with jQuery and JavaScript

I've been exploring jQuery and trying to update a specific TD element with innerHTML. However, I'm stuck on how to capture the value of a parameter. In this scenario, my goal is to grab the user-id "1234" in order to update the TD identified as ...

Tips for obtaining an Instance of a Mat-Table when there are multiple tables within the component

Encountering an issue where I have a component in Angular 6 generating multiple Mat-Tables with Data. Using the ng-for loop to iterate through all the Mat-Table Data sources within a div tag. However, when trying to add a new row to a table, unable to iden ...

Is there a way to programmatically update a webpage using Javascript?

I have been attempting to set up the code in a way that the page automatically changes using setTimeout. However, I am unable to make it work. setTimeout()(page3, 500); function page3() { changepage3('automatic') } Even though my code is str ...

trpc - Invoking a route from within its own code

After reviewing the information on this page, it appears that you can invoke another route on the server side by utilizing the const caller = route.createCaller({}) method. However, if the route is nested within itself, is it feasible to achieve this by ...

Arranging Typescript strings in sequential date format

Looking for guidance on how to sort string dates in chronological order, any expert tips? Let's say we have an array object like: data = [ {id: "1", date: "18.08.2018"} {id: "2", date: "05.01.2014"} {id: "3", date: "01.01.2014"} {id: ...

Discovering whether a link has been clicked on in a Gmail email can be done by following these steps

I am currently creating an email for a marketing campaign. In this email, there will be a button for users to "save the date" of the upcoming event. I would like to implement a feature that can detect if the email was opened in Gmail after the button is cl ...

Animating Text Changes with JavaScript and jQuery

In my HTML, I have an input type="text" element and I want to attach an event handler that triggers when the text is changed. The issue arises because this input's value is dynamically updated by another JavaScript function, causing the event handler ...

Creating a Dynamic Slideshow on Autopilot

My JavaScript skills are not perfect and I'm feeling a bit lost. I have this code for a slideshow, but I want to make it automatic while also allowing users to navigate between images freely. I'm struggling to figure out how to implement this fun ...

What is the best way to set a value in PHP that can be utilized as flight plan coordinates on a Google Map within my script?

I am looking to dynamically update the content of my div with id "map" in response to button clicks, where the flight plan coordinates are changing. Currently, I have attempted to achieve this by assigning PHP output to a JavaScript variable as shown below ...

Adding a function to the Window in React & Next.js without using the onload event

Issue with External Script in React Next.js Project I am facing a problem with an external script within my React Next.js project. The script is located at . The script does not work correctly when navigating to the page using the next/link component fro ...

When attempting to replace the outdated Angular 2 router with the new Router, I encountered an error

I have the main app component and I want to add subroutes under the admin component like /admin/users, /admin/subscribers @Component({ selector: 'my-app', template: `<router-outlet></router-outlet>` directives: [ROUTER_DI ...

Is it possible to change the return value of an Object key to something other than a string in REACT? Issue with RE

In an attempt to modify the data in an object using the setState method in 'react', I decided to take a different approach. Instead of creating a function for each key in the state object, I attempted to create one object and return the key from ...

Troubles with Angular elements not aligning correctly when using the "display: block" property

When using an angular element for a directive with "display: block", it may not automatically take up 100% of the width of the parent container. In order to ensure that it does, the width must be explicitly set to "100%" in the CSS. Despite setting "width: ...

Struggling to implement nested routes with react-router-dom version 5.2.0?

I'm currently working on implementing nested routing in React using react-router-dom 5.2.0. For a better understanding of the project, you can access the CodeSandbox link here: https://codesandbox.io/s/nested-routes-8c7wq?file=/src/App.js Let's ...