Angular2 传递函数作为组件输入不起作用 [英] Angular2 passing function as component input is not working

查看:34
本文介绍了Angular2 传递函数作为组件输入不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将函数作为输入的组件.我已经从父级传递了这个函数.

I've a component that takes function as input. I've passed this function from parent.

尽管调用了该函数,但该函数无法访问声明该函数的实例的依赖项.

Though the function is called, the function is not able to access the dependencies of the instance on which this function is declared.

这是组件

@Component({
  selector: 'custom-element',
  template: `
    {{val}}
  `
})
export class CustomElement {
  @Input() valFn: () => string;

  get val(): string {
    return this.valFn();
  }
}

这里是组件的使用方法

@Injectable()
export class CustomService {
  getVal(): string {
    return 'Hello world';
  }
}

@Component({
  selector: 'my-app',
  template: `
   <custom-element [valFn]="customVal"></custom-element>
  `,
})
export class App {
  constructor(private service: CustomService) {
  }
  customVal(): string {
    return this.service.getVal();
  }
}

当我运行这个应用程序时,我在控制台中收到一个错误消息,说Cannot read property 'getVal' of undefined

When I run this app, I get an error in the console saying Cannot read property 'getVal' of undefined

这是一个问题.

https://plnkr.co/edit/oQ229rXqOU9Zu1wQx18b?p=preview

推荐答案

如果你传递方法,你需要.bind(this):

You need to .bind(this) if you pass methods around:

<custom-element [valFn]="customVal.bind(this)"></custom-element>

export class App {
  constructor(private service: CustomService) {
  }
  customVal(): string {
    return this.service.getVal();
  }
  customValFn = this.customVal.bind(this);
}

<custom-element [valFn]="customValFn"></custom-element>

这篇关于Angular2 传递函数作为组件输入不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆