0

How can I access other components that are in the same view but aren't children? My parent component has some components.

parent.component.html

<html>
  <address-component></address-child>
  <name-component></name-component>
</html>

So how can I access name-component from the address-component? They do not have a relationship of their own except that they lie in the same view.

anonymoose
  • 1,169
  • 2
  • 21
  • 62
Janier
  • 3,982
  • 9
  • 43
  • 96
  • 1
    That depends on what it is you are trying to accomplish. Inter-component communication is not an end in itself. – Igor Jan 25 '18 at 21:00
  • I want to get the name component which is in the view and invoke a method with in the name component from the address component. – Janier Jan 25 '18 at 21:01
  • You could abstract the method responsible for creating the name into a service and inject that service into both components. – Igor Jan 25 '18 at 21:02
  • I know that.I am looking for ways not to do it since my detailed use case wont suit it.I am looking for ways within the component .something like access the form and get the name -component from within it or something like that. – Janier Jan 25 '18 at 21:04
  • Can you explain why what your use case is, and why a shared service doesn't suit? Otherwise this just comes across as an [XY problem](http://xyproblem.info) – match Jan 25 '18 at 21:08
  • `since my detailed use case wont suit` <= Then I recommend you provide a better / updated question with the details of what it is you are trying to accomplish. As it stands now your question is rather vague so in the event you do get an answer it will likely not answer your question. – Igor Jan 25 '18 at 21:09
  • 1
    You could pass the `name` component as an input parameter to the `address` component, as shown in [this stackblitz](https://stackblitz.com/edit/angular-t6kv6c) (see the template in app.component.html). – ConnorsFan Jan 25 '18 at 21:15
  • Follow these already answered questions: 1. [First](https://stackoverflow.com/questions/45170463/how-can-i-access-from-a-child-component-to-another-child-component-in-angular-4) 2. [Second](https://stackoverflow.com/questions/41954484/communicate-between-two-child-components-in-angular-2) – Sujil Maharjan Jan 25 '18 at 21:08

1 Answers1

1

If you don't want to use a service, you can try this child1-parent-child2 communication:

<address-component (updateNameComponent)="nameComponent.yourMethodName()"></address-child>
<name-component #nameComponent ></name-component>

And in your address component, you would have this:

@Output() updateNameComponent = new EventEmitter();

and you can trigger nameComponent.yourMethodName from address component using this:

updateNameComponent.emit();
Uğur Dinç
  • 2,415
  • 1
  • 18
  • 25