首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@Query未找到组件引用

@Query未找到组件引用
EN

Stack Overflow用户
提问于 2015-09-20 23:41:57
回答 1查看 180关注 0票数 1

我已经创建了一个在内部使用子组件的父组件。我的目标是让父组件使用子组件API,但我遇到了麻烦。下面是我的代码,精炼/压缩到相关区域。

代码语言:javascript
复制
class TripStop {}

@Component({
  selector: 'route-map'
})
@View({
  template: '...'
})
class RouteMap {

  setRoute(route: TripStop[]) {
    // Set the route!
  }

}

@Component({
  selector: 'route-plan'
})
@View({
  template: `
    <div>
      ...
      <route-map></route-map>
    </div>
  `,
  directives: [RouteMap]
})
class RoutePlan {

  private stops: TripStop[];
  private maps:QueryList<RouteMap>;

  constructor(@Query(RouteMap) maps:QueryList<RouteMap>) {
      this.maps = maps;
    }

  public addStop() {
    this.stops.push(new TripStop());

    var routeMapComponent = this.maps.first; // This evaluates to undefined.
    routeMapComponent.setRoute(this.stops);
  }
}

到目前为止,我还无法在我的plan-route组件中获得对子路由映射组件的引用。根据我在Angular 2.0 documentation上所读到的内容,似乎我应该能够使用@Query装饰器来注入对匹配查询的任何子组件的引用(作为ComponentRef对象)。

我尝试在查询@Query(RouteMap)中使用组件类型,并添加对地图元素<route-map #myMap></route-map>的引用,然后使用该@Query('myMap')进行查询。

令人困惑的是,我设法让@ViewQuery装饰器正常工作,并通过向我的元素添加一个引用来返回对映射不足的DOM元素的引用&如上所述使用该引用进行查询。这对我没有真正的帮助,因为我更愿意通过它的API与我的组件通信,而不是修改它的底层DOM -然而,我认为这表明我的应用程序的总体连接正在按预期工作。

这里我漏掉了什么?

编辑:我使用的是2.0.0-alpha.37版本。

EN

回答 1

Stack Overflow用户

发布于 2015-09-21 06:14:58

2.0.0-alpha.37版本中,要获得对子指令的引用,可以使用@ViewQuery装饰器,并传递该子组件的类型。要获得一个子DOM元素,可以使用@ViewQuery装饰器,传递对该元素的引用。

代码语言:javascript
复制
@Component({
  selector: 'Child'
})
@View({
  template: '<h1>I'm a child</h1>'
})
class Child {}

@Component({
  selector: 'Parent'
})
@View({
  template: '<child #myComponent></child>',
  directives: [Child]
})
class Parent {

  private childDirectives:QueryList<Child>;
  private childViews:QueryList<Child>;

  constructor(
    @ViewQuery(Child) childDirectives:QueryList<Child>,
    @ViewQuery('myComponent') childViews:QueryList<ElementRef>
  ) {
    // A query list of Child components.
    this.childDirectives = childDirectives;
    // A query list of views with the id #myComponent.
    this.childViews = childViews;
  }
}

我不确定@Query的角色是什么,也不确定@ViewQuery是否接受除ID之外的任何其他选择器。这种行为似乎没有被很好地记录下来,而且似乎有点不直观--然而,看起来API在这方面仍然在变化(#3922)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32681191

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档