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
这是一个问题的掠夺者.
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)
| 归档时间: |
|
| 查看次数: |
12802 次 |
| 最近记录: |