【问题标题】:NgComponent: How to get component instance from DOM element?NgComponent:如何从 DOM 元素中获取组件实例?
【发布时间】:2014-01-23 04:17:38
【问题描述】:

我创建了一个NgComponent 并在标记中声明了它。是否可以查询组件元素并获取关联的NgComponent实例?

【问题讨论】:

    标签: dart angular-dart


    【解决方案1】:

    通常您不需要通过元素访问控制器。也就是说,有introspection APIngDirectives 将返回给定节点的所有控制器列表。 但 AFAIK 仅用于调试

    或者,如果您需要访问子组件/指令/控制器,请考虑以下模式:

    <tabs>
      <pane title="Pane A">...</pane>
      <pane title="Pane B">...</pane>
      <pane title="Pane C">...</pane>
    </tabs>
    
    @NgComponent(
        selector: 'tabs',
        visibility: NgDirective.DIRECT_CHILDREN_VISIBILITY
    )
    class Tabs {
      List<Pane> _panes;
    
      registerPane(Pane pane) {
        _panes.add(pane);
      }
    }
    
    @NgComponent(
        selector: 'pane'
    )
    class Pane {
      @NgAttr('title')
      String title;
    
      Pane(Tabs tabs) {
        tabs.registerPane(this);
      }
    }
    

    当窗格被实例化时,它们会向选项卡容器自行注册,随后选项卡容器可以访问窗格实例。

    【讨论】:

    • 感谢帕维尔的回复。但是,我并没有尝试通过元素访问控制器。我正在尝试通过控制器访问 NgComponent 实例。我已经使用 scope.$broadcast 和 scope.$on 在组件上调用预期的方法来解决这个问题。
    • 澄清一下,您是否尝试从另一个组件访问一个组件?
    • 我正在尝试从控制器中访问组件。
    • Angular.dart 命名法有时会让人感到困惑......所以你有一个@NgComponent@NgController,你想从@NgController 访问@NgComponent@NgController@NgComponent 的孩子吗?
    • NgComponentNgController 的子代。所以,在NgController 中,我打电话给_scope.$broadcast('messageForComponent'),在NgComponent 中,我正在收听该消息:_scope.$on('messageForComponent', () =&gt; ...)。这是可行的,但我的初衷是直接获取NgComponent 的实例。我最初是在聚合物中执行此操作的,您将在其中 querySelector 元素,它组件的实例。
    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 2018-10-25
    • 2016-08-02
    • 2013-08-04
    • 2016-02-21
    相关资源
    最近更新 更多