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

Ash*_*oyi 10 angular2-template angular2-di angular

我有一个将函数作为输入的组件.我从父母传递了这个功能.

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

这是组件

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

  get val(): string {
    return this.valFn();
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是组件的使用方法

@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();
  }
}
Run Code Online (Sandbox Code Playgroud)

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

这是一个问题的掠夺者.

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

Gün*_*uer 18

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

<custom-element [valFn]="customVal.bind(this)"></custom-element>
Run Code Online (Sandbox Code Playgroud)

要么

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

<custom-element [valFn]="customValFn"></custom-element>
Run Code Online (Sandbox Code Playgroud)

  • 这是"正常";-)或"默认"JS行为.如果你传递方法或函数引用`this`,你必须使用`.bind(this)`或箭头函数(如`[valFn] ="()=> customVal()"`但不支持在模板绑定AFAIR中. (2认同)
  • "默认"行为是"this"指向函数的调用者,而不是声明者. (2认同)