Home > OS >  passing method reference in object and calling it raising the problem , the constructor inject depen
passing method reference in object and calling it raising the problem , the constructor inject depen

Time:08-19

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
    
    [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

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

CodePudding user response:

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',
}
  • Related