gpt4 book ai didi

callback - 使用回调函数作为组件 @Input() 时的 Angular2 undefined object 属性

转载 作者:太空狗 更新时间:2023-10-29 17:30:52 25 4
gpt4 key购买 nike

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

应用.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);

我的组件.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 组件,这直接从应用程序调用 appOnClick 函数,单击时控制台显示:
- 从应用程序点击
- 这应该有一个值

BUTTOM INSIDE COMPONENT,这通过组件中的@Input 函数调用appOnClick 函数,单击时控制台显示:
- 从应用程序点击
- 不明确的

我在 Plunker 上创建了示例

这是一种正确分配 this 的方式,以便我可以在触发回调时使用我的对象属性吗?

最佳答案

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

关于callback - 使用回调函数作为组件 @Input() 时的 Angular2 undefined object 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36381333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com