The ngOnChanges method in Angular is unable to access instance properties that are dynamically set

Could someone clarify the reason why this.agGrid is showing as undefined in the ngOnChanges method? Despite being set in onGridReady, which runs before the ngOnChanges method.

Within my component.ts file:

  private onGridReady(agGrid) {
    this.agGrid = agGrid;
    console.log(1, this.agGrid);

  }
  ngOnChanges(changed) {
    console.log(2, this.agGrid);  
  }

console output:

1 Object { type: "gridReady", api: {…}, columnApi: {…} }
2 undefined

Any thoughts on why this.agGrid is not defined in ngOnChanges?

Edit (demonstrating how onGridReady is called):

html

<ag-grid-angular
    class="ag-theme-balham"
    style="width: 100%; height: 100%;"
    [gridOptions]="gridOptions">
</ag-grid-angular>

more from the ts file

  private createGridOptions() {
    const gridOptions = {};
    gridOptions['onGridReady'] = this.onGridReady;
    return gridOptions;
  }
  ngOnInit() {
    this.gridOptions = this.createGridOptions();
  }

Answer №1

By assigning the function directly, you are essentially performing the same action as if you were calling onGridReady within a function() { }. Within a function() { }, the keyword this refers to the function itself.

It's important to note that you're not updating the agGrid property on the component; instead, you're setting a property on the function itself.

To reference the outer scope - in this case, the component - it is recommended to use an arrow function.

gridOptions['onGridReady'] = (agGrid) => this.onGridReady(agGrid);

Check out the DEMO: https://stackblitz.com/edit/angular-ay79o3

In the demonstration provided, button 1 will not set the name property on the component correctly due to how it is called. On the other hand, button 2 will successfully set the name property on the component because it is invoked inside an arrow function.

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

TypeScript disregards interface method argument types

Unexpectedly, the code below compiles without any errors (using tsc 3.9.5): interface IDateHandler { handleDate: (Date) => void; } let dateHandler: IDateHandler = { handleDate: (d: Date) => {}, }; dateHandler.handleDate([1, 2, 3]); Even more s ...

Tips for sorting and categorizing information within Angular version 14

When I press "All," I want to see the status of P and step 01, along with its type. Thank you very much. This is in HTML: <mat-form-field appearance="outline"> <mat-select (selectionChange)="onChange($event)"> ...

What steps can be taken to address the build problem with Angular version 13?

Encountering a problem while working with Angular 13: https://i.sstatic.net/CbAUhh6r.png Attempting to build using ng build --configuration=test, however facing errors as mentioned above. Interestingly, if I remove the reference to bootstrap.min.css in t ...

Modify the animation attribute of the <circle> element using AngularJS

A new feature I implemented in my web app is a customizable countdown timer. As an added visual enhancement, I am now looking to create an animated circle around the timer. The animation duration will vary based on the countdown length. Here is a snippet ...

Encapsulate the HTTP request within a common function for reus

My rest-provider service handles all of my http calls, but I've noticed that each function is repeating a lot of the same http code. It seems like I should create a shared function to avoid this repetition and make it easier to update in the future. ...

Tips for implementing lazy loading of modals in Angular 7's module structure

In a previous project, our team utilized a single "app module" that imported all necessary components, pipes, directives, and pages at the beginning of the application. However, this structure was not ideal as the app became slower with its growth. Upon t ...

Issue with Angular and rxjs: Subscription provider not found

Trying to establish communication between a service and component in Angular, where the service holds a value and the component subscribes to its changes. Currently utilizing rxjs Subscription, but encountering an issue: Uncaught (in promise): Error: No p ...

Utilizing the combination of attribute binding and string interpolation

Looking to create an accordion similar to the one showcased on the Bootstrap website, but with the twist of dynamically loading data using Angular 2's *ngFor directive. I attempted setting the value of aria-controls dynamically like so: [attr.aria-co ...

Ignoring certificates when using ng-serve in Angular framework is common practice

I'm trying to host an Angular application securely over HTTPS by using ng-serve --host 0.0.0.0. The project I'm working on is built with Angular CLI version 1.2. However, Angular seems to ignore the certificates I provide and generates its own i ...

Styling with react-jss based on intricate conditionals

After experimenting with react-jss for a few weeks, I am faced with the challenge of styling components efficiently. With numerous conditionals in these components, I am striving to avoid creating an excess of new components that essentially share the same ...

When subscribed to, the BehaviorSubject will return the object twice

When working with a bank API for payments, the response expected by the banks is that Ban Pay JavaScript will perform an HTTP redirect in the top frame to a completeUrl. The question arises - what should be the completeUrl that I need to provide to the ban ...

Error encountered when attempting to implement Material Angular 2 autocomplete functionality

I encountered an issue with Angular 2 while integrating autocomplete in material design. This is my first attempt at implementing it along with practicing backend ASP.net Core. Despite trying to install some ng2 libraries, I still couldn't get it to w ...

Tips for setting the scroll back to the top when switching between pages in quasar

Whenever a qlist item is clicked by the user, it redirects to another page. However, the scrolled position from the previous page is retained and not set to the top. This means that the user has to manually scroll back to the top to view the contents of th ...

Using Angular to conditionally import a JSON file

Struggling to find a way forward, I've come across 4-5 JSON files with similar structures but different values. My goal is to load the appropriate JSON file based on a value stored in localStorage. Currently, I am loading a file at the top: import * ...

Tips on clearing and updating the Edit Modal dialog popup form with fresh data

This code snippet represents my Edit button functionality. The issue I am facing is that I cannot populate my Form with the correct data from another component. Even when I click the (Edit) button, it retrieves different data but fails to update my form, ...

Step-by-step guide to creating an nx workspace using Angular 14

Transitioning to an nx workspace with 2 apps and 2 libraries, all utilizing angular version 14, has been a challenge due to being locked into this version for compatibility with ionic 5. Despite various attempts to set up the workspace, I have yet to succe ...

The CSS scale property is not working as expected when used in a React.js application, specifically

working environment ・next.js ・react ・typescript https://www.youtube.com/watch?v=ujlpzTyJp-M A Toolchip was developed based on the referenced video. However, the --scale: 1; property is not being applied. import React, { FunctionComponent ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

Setting the data type for a React Stateless Functional Component (SFC) in TypeScript

By assigning a type of React.FC<PropsType> to a variable, it becomes recognized as a React Stateless Functional Component. Here's an example: //Interface declaration interface ButtonProps { color: string, text: string, disabled?: boolean ...

saveToPhotoAlbum functionality not functioning as expected on both Android and iOS platforms

Everything in my ionic 4 app seems to be working fine, from taking pictures with the camera plugin to uploading them to a remote server. I can even access images from the gallery on another page. However, there's one issue that I can't seem to fi ...