Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

passing method reference in object and calling it raising the problem , the constructor inject dependency coming as undeifined

here the link for the stackblits stackBlits Example
here i created the array and passed the method reference in the object of array but i getting undefined for the constructor injected property

import { HttpClient } from '@angular/common/http';
import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  constructor(public http: HttpClient) {
    alert(http);
  }

  PrintTwo() {
    alert(this.http);
    alert('two');
  }
  btns: Array<any> = [
    {
      name: 'two',
      title: 'two',
      functionToCall: this.PrintTwo,
      class: 'btn-danger',
    },
  ];
}

here is HTML part

  <ng-container *ngFor="let btn of btns">
  <button
    class="btn me-4 {{ btn.class }}"
    [title]="btn.title"
    #btnElement
    (click)="btn.functionToCall()">
    {{ btn.name }}
  </button>
</ng-container>

here from constructor in alert object is coming but when calling from a method it is coming as undefined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i dont know why it behaving like this , i think when i am passing the method whole complete method is passed and there is no other properties means it does not taking class method as refrence all it is doing taking method code directly in method

>Solution :

The expression btn.functionToCall() is called in the context of btn. It means that this points to:

{
  name: 'two',
  title: 'two',
  functionToCall: this.PrintTwo,
  class: 'btn-danger',
}

Try to bind the PrintTwo to the correct context:

{
  name: 'two',
  title: 'two',
  functionToCall: this.PrintTwo.bind(this),
  class: 'btn-danger',
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading