使用回调函数作为组件@Input()时的Angular2 Undefined Object属性

时间:2016-04-03 03:32:02

标签: callback typescript angular

我试图将回调函数绑定到指令,当事件被触发时,父组件的属性是未定义的

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;

}

这将呈现两个按钮:

BUTTOM OUTSIDE COMPONENT,直接从应用程序调用appOnClick功能,点击控制台显示:
- 点击APP
- 这应该有价值

BUTTOM INSIDE COMPONENT,它通过组件中的@Input函数调用appOnClick函数,当单击控制台显示时:
- 点击APP
- 未定义

我在Plunker

上创建了示例

这是一种正确分配的方法,这样当触发回调时我可以使用我的对象属性吗?

2 个答案:

答案 0 :(得分:12)

Updated plunkr

为了以这种方式传递appOnClick,您需要将其声明为如下属性:

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

而不是:

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

答案 1 :(得分:0)

我认为你忘了&#34;(...)&#34;当使用appOnClick方法并使用&#34; [...]&#34;而不是&#34;(...)&#34;配置事件处理程序时:

<my-component (onClick)="appOnClick($event)"></my-component>`,

此外,在您的子组件中,您需要使用&#34; @输出&#34;来定义自定义事件:

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

  handleClick(txt:string) {
    this.onClick.emit(txt);
  }     
}