简体   繁体   English

访问组件B中组件A的属性?

[英]Accessing the properties of component A in component B?

I can't use @Input , because the two components are far apart in the components tree. 我不能使用@Input ,因为组件树中的两个组件相距很远。

Using a service looks like the only option, but it seems very overkill to have a service that is essentially a duplicate of all component's A properties. 使用服务看起来是唯一的选择,但是拥有一个基本上与所有组件的A属性重复的服务似乎非常难以理解。 Every time I set a property in A, I would also need to set it in the service so that B has access to it. 每次我在A中设置属性时,我还需要在服务中设置它,以便B可以访问它。 Doesn't seem very efficient. 看起来效率不高。

Isn't there a way to inject the instance of component A in component B? 有没有办法在组件B中注入组件A的实例? Note that A isn't a parent/child of B. 请注意,A不是B的父/子。

Cheers! 干杯!

You can bind to a property of a service 您可以绑定到服务的属性

@Component({
  ...
  template: <div>{{myService.someProp}}</div>
})
class MyComponent {
  constructor(private myService:MyService){}
}

then you don't need to duplicate. 那你就不需要复制了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM