2

I have two components: ComponentOne and ComponentTwo.

@NgComponent(...)
class ComponentOne {
}

<div>
  <h1>Component One</h2>
  <content></content>
<div>

@NgComponent(...)
class ComponentTwo {
}

<div>
  <h1>Component Two</h2>
<div>

Then I have the following markup:

<component-one>
  <component-two></component-two>
</component-one>

How do I reference ComponentTwo from ComponentOne. To be more specific, I have a method which handles click event and needs to delegate that click event to it's child. Which is the best way to do that?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
markovuksanovic
  • 15,676
  • 13
  • 46
  • 57

2 Answers2

1

I would inject ComponentOne to ComponentTwo and in the constructor of ComponentTwo assign ComponentTwo to ComponentOne.

 ComponentTwo(ComponentOne c1) {
   c1.componentTwo = this;
 }

You could also create a Directive that does only that, to avoid tight coupling of ComponentTwo to ComponentOne.

AssignComponentTwoDirective(ComponentOne c1, ComponentTwo c2) {
  c1.componentTwo = c2;
}

Maybe there is a better way but I didn't see one yet.

You have to set visibility of ComponentOne to children.

@NgComponent(
  selector: 'component-one',
  visibility: NgDirective.CHILDREN_VISIBILITY,
  ...)
class ComponentOne ...

See also angular 2 / typescript : get hold of an element in the template

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I don't like the idea of injecting componentOne into componentTwo. The idea is that componentOne can have a child. In case something happens in ComponentOne it needs to be delegated to child. In this case it's componentTwo but it may as well be some other component. The idea is to make components reusable. They shouldn't know anything about each other. Component one should only know that it has a child and it can invoke method (i.e. click) on that child. Child can be any component that has click method. – markovuksanovic Feb 13 '14 at 12:46
  • I don't like it either but couldn't yet find a better solution. – Günter Zöchbauer Feb 13 '14 at 12:48
  • Another possibility: ComponentTwo could assign itself to the scope of the parent `scope.$parent['componentTwo'] = this;` and ComponentOne could add a watch to get notified when `scope['componentTwo'] was set and then access it. It should also be possible to emit events that the child can receive. – Günter Zöchbauer Feb 13 '14 at 14:17
0

The answer to your question resides in this tutorial page : https://angular.io/docs/dart/latest/tutorial/toh-pt3.html

Actually you can use the @Input parent directive in your component to link it to its parent in an abstract manner with a "target attribute property" [parent]=me

You can therefore declare an interface you expect the parent to implement to have a unidirectional link

Zied Hamdi
  • 2,400
  • 1
  • 25
  • 40