我试图将回调函数绑定到指令,当事件被触发时,父组件的属性未定义
应用程序
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函数,当单击控制台时显示:
-从应用程序中单击
-应该具有一个值
BUTTOM INSIDE COMPONENT,它通过组件中的@Input函数调用appOnClick函数,当单击控制台时显示:-CLICK
FROM APP
-undefined
我已经在Plunker上创建了示例
这是一种正确分配此方法的方法,以便在触发回调时可以使用我的对象属性吗?
为了通过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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句