2016-04-03 50 views
4

进出口试图当事件被触发的父组件的属性的回调函数绑定到一个指令,是不确定的用回调函数作为组分@input()时Angular2未定义的对象属性

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); 

我-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的外部元件,这将调用appOnClick功能从应用程序直接点击控制台时表示:
- 点击来自APP
- 这应该有一个值

BUTTOM内部的元件,这个调用通过在组件,单击控制台当@input功能appOnClick功能显示:
- 点击来自APP
- 未定义

我已经创建于Plunker

的例子是,当回调触发正确地分配这个,所以我可以用我的对象工作方式的属性?

回答

11

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); 
    } 
} 
+0

谢谢你,伙计!它像一个魅力。 – Mush

+0

@Mush - 没问题:-)如果这个答案解决了这个问题,请考虑接受它 – drewmoore

+0

做,对不起,我已经错过了!欢呼的队友! – Mush

0

我认为你忘“(...)”使用appOnClick方法和使用时“[...]”代替“(...)”配置事件处理程序时:

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

而且你的子组件中,你需要用“@Output”定义自定义事件:

@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); 
    }  
} 
相关问题