Angular:来自其他组件的调用函数 [英] Angular: call function from other component
本文介绍了Angular:来自其他组件的调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制作两个角度组件,我想从第二个组件中的第一个组件调用一个函数。当我尝试这个时,我收到以下错误消息:未定义
的red属性'functionName'。如何解决这个问题?
I'm trying to make two angular components and I want to call a function from the first component in the second component. When I try this I get following error message: Cannot red property 'functionName' of undefined
. How can this be solved?
这里有一个例子的链接: https://stackblitz.com/edit/angular-rre4gb
Here a link of an example: https://stackblitz.com/edit/angular-rre4gb
推荐答案
那是因为组件你想调用它的函数,没有实例化。
That's because the component you want to call its function, is not instantiated.
对于组件通信你可以使用服务
代替:
for component communication you can use a service
instead:
@Injectable()
export class MyService {
myCustomFunction(){
}
}
$ b组件中$ b
组件
:
Component
in your component:
@Component({
selector: 'my-component',
providers: [ MyService ]
})
export class MyComponent {
// inject your service to make it available
constructor(private service: MyService){}
doStuff(){
// call function which is located in your service
this.service.myCustomFunction();
}
}
这篇关于Angular:来自其他组件的调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文