[英]How to call method of another component in Angular 8
I've explain the scenario in Image. 我已经解释了Image中的场景。
I've one LayoutComponent , 我有一个LayoutComponent ,
In which I have 1) LeftMenuComponent and 2) Router-Outlet In side the LeftMenuComponent I've LoyaltyComponent which is coming from Shared Folder . 在其中,我有1) LeftMenuComponent和2) 路由器插座在LeftMenuComponent旁边,我有LoyaltyComponent ,它来自Shared Folder 。
I want to call LoyaltyComponent ngOnInit method from any component inside RouterOutlet. 我想从RouterOutlet内部的任何组件调用LoyaltyComponent ngOnInit方法。
Please Note: LoyaltyComponent is inside Shared Folder and OrderListComponent is inside Order Folder. 请注意:LoyaltyComponent位于共享文件夹内,而OrderListComponent位于订单文件夹内。
Is there any way I can call cross component method or all I need is I want to refresh LoyaltyComponent from OrderList Component. 有什么方法可以调用跨组件方法,或者我需要从OrderList Component刷新LoyaltyComponent。
I've tried: 我试过了:
@ViewChild('Loyalty') private loyaltyComponenet : Loyalty;
But it is giving me undefined. 但这给了我不确定的信息。
Also from using behaviourSubject, can I directly call ngOnInit of LoyaltyComponent?
LoyaltyComponent.ts LoyaltyComponent.ts
export class Loyalty implements OnInit {
public loyaltyMet: number;
public loyaltyThreshold: number;
public loyaltyBarWidth: number;
public loyaltyRequired : number;
constructor() {
}
public ngOnInit(): void {
this.loyaltyMet = Context.loyaltyMet;
this.loyaltyThreshold = Context.loyaltyThreshold;
this.loyaltyRequired = this.loyaltyThreshold - this.loyaltyMet;
this.loyaltyBarWidth = this.loyaltyMet * 100 / this.loyaltyThreshold;
if (this.loyaltyRequired < 0) {
this.loyaltyRequired = 0;
this.loyaltyBarWidth = 100;
}
}
}
I believe Context
is being injected via the constructor, is that a service ? 我相信Context
是通过构造函数注入的,这是一种服务吗?
you can have a method on that service saying "refresh" or something, that when triggered, emits a value via a simple subject. 您可以在该服务上使用一个方法,说“刷新”或类似的内容,该方法在触发时会通过一个简单的主题发出一个值。
your Loyalty component, can, oninit, subscribe to that subject, and react to it when its triggered. 您的忠诚度组件可以oninit订阅该主题,并在其触发时对其做出反应。
as long as the Context
service is being used as a singleton for all consumers (as in, provided once) you should be good to go. 只要将Context
服务用作所有消费者的单例用户(如提供一次),您就应该可以使用。
如果组件是父级和子级,则使用@Input
和@Output
,如果不是,则使用EventEmitter
这是解决方案https://stackoverflow.com/a/57324581/2762191
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.