2015-09-20 25 views
1

我已經創建了一個父組件,它在內部使用了一個子組件。我的目標是讓父組件使用我的子組件API,但我遇到了麻煩。以下是我的代碼精煉/濃縮到相關領域。@Query未找到組件引用

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

回答

1

從版本2.0.0-alpha.37開始,要獲得對子指令的引用,可以使用@ViewQuery修飾符,傳遞子組件的類型。要獲得子DOM元素,可以使用裝飾器@ViewQuery,傳遞元素的引用。

@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)。