Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Undefined Object attribute when using a callback function as Component @Input()

Im trying to bind a callback function to a directive, when the event is fired the attribute of the parent component are undefined

app.ts

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {MyComponent} from './my-component';

@Component({
  selector: 'my-app',
  template: `
  <button (click)="appOnClick('CLICK FROM APP')">BUTTOM OUTSIDE COMPONENT</button>
  <br><br>
  <my-component [onClick]="appOnClick"></my-component>`,
  directives: [MyComponent]
})
export class MyApp { 
  
  public theBoundCallback: Function;
  test:string = "THIS SHOULD HAVE A VALUE";
  
  public ngOnInit(){
    this.theBoundCallback = this.appOnClick.bind(this);
  }
  
  appOnClick(someText){
    
    console.log(someText);
    console.log(this.test);
    
  }
}

bootstrap(MyApp);

my-component.ts

import {Component, Input} from 'angular2/core';

@Component({
  selector: 'my-component',
  template: `<button (click)="onClick('CLICK FROM COMPONENT')">BUTTOM INSIDE COMPONENT</button>`
})
export class MyComponent{

  @Input() onClick: Function;
  
}

That will render two buttons:

BUTTOM OUTSIDE COMPONENT, this calls the appOnClick function direct from the app, when clicked the console shows:
- CLICK FROM APP
- THIS SHOULD HAVE A VALUE

BUTTOM INSIDE COMPONENT, this calls the appOnClick function via the @Input function in the component, when clicked the console shows:
- CLICK FROM APP
- undefined

I've created the example on Plunker

Is that a way to assign this correctly so I can work with my object attributes when the callback is trigger?

like image 418
Mush Avatar asked Apr 03 '16 03:04

Mush


1 Answers

Updated plunkr

In order to pass appOnClick around this way, you need to declare it as a property like so:

export class MyApp {
  ...
  appOnClick = (someText) => {
    console.log(someText);
    console.log(this.test);
  }
} 

instead of:

export class MyApp {
  ...
  appOnClick(someText){
    console.log(someText);
    console.log(this.test);
  }
} 
like image 151
drew moore Avatar answered Nov 15 '22 02:11

drew moore