我有一个将函数作为输入的组件.我从父母传递了这个功能.
虽然调用了该函数,但该函数无法访问声明此函数的实例的依赖项.
这是组件
@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
这是一个问题的掠夺者.
虽然这个答案可能很简单,但我似乎陷入困境.作为Angular 2的初学者,我尝试了{},[]和()括号的所有可能组合来实现以下目的:
<button (click)="this.action">Click me</button>
Run Code Online (Sandbox Code Playgroud)
哪里:
this.action = "clickMe()"
Run Code Online (Sandbox Code Playgroud)
即它是一个字符串,该组件中应该在点击时执行的方法的名称.
有任何想法吗?