本文介绍了如何在 AngularDart 中从其父组件引用子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个组件:ComponentOneComponentTwo.

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>

然后我有以下标记:

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

如何从 ComponentOne 引用 ComponentTwo.更具体地说,我有一个处理点击事件的方法,需要将该点击事件委托给它的子级.哪种方法最好?

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?

推荐答案

我会将 ComponentOne 注入 ComponentTwoComponentTwo 的构造函数中将 ComponentTwo 分配给 ComponentOne.

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

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

您也可以创建一个仅执行此操作的指令,以避免 ComponentTwo 与 ComponentOne 紧密耦合.

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.

您必须将 ComponentOnevisibility 设置为 children.

You have to set visibility of ComponentOne to children.

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

另见 angular2/typescript : 获取模板中的元素

这篇关于如何在 AngularDart 中从其父组件引用子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 18:47