How to reference child component from its parent in AngularDart

元气小坏坏 提交于 2019-12-11 02:59:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!