问题
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?
回答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
回答2:
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
来源:https://stackoverflow.com/questions/21754244/how-to-reference-child-component-from-its-parent-in-angulardart