Angular2 传递函数作为组件输入不起作用

2023-11-22

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

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

这是组件

@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

这是这个问题的一个解决方案。

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


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

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

or

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

with

<custom-element [valFn]="customValFn"></custom-element>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular2 传递函数作为组件输入不起作用 的相关文章

随机推荐