2016-01-24 80 views
4

我正在構建角2中的模態服務。我解決了大多數問題,但是我有問題將模態組件以正確的方式放置在body元素中。我使用DynamicComponentLoader.loadNextToLocation函數來獲取模態組件,並將其放置在ElementRef的哪個位置用於DynamicComponentLoader.loadNextToLocation函數。但是,當我不想將創建的模態放在某個組件中時,我必須操縱DOM來插入創建的模態。我的問題是我可以在模態服務中使用我的應用程序中的根元素嗎?當特定的元素沒有作爲容器提供給模態時,我想實現這一點。獲取根組件ElementRef或ComponentRef angular 2

var elementRef = DOM.query('app'); 
this.componentLoader.loadNextToLocation(ModalBackdrop, elementRef, backdropBindings) 

回答

4
appElementRef: ElementRef; 
constructor(private applicationRef:ApplicationRef, injector: Injector) { 
    this.appElementRef = injector.get(applicationRef.componentTypes[0]).elementRef; 
} 

AppComponent需要提供elementRef場,雖然返回ElementRef

又見https://github.com/angular/angular/issues/6446

4

要正本清源組件的引用,你可以注入ApplicationRef

constructor(private app:ApplicationRef) 
{ 
     let element: ElementRef = this._app['_rootComponents'][0].location; 
} 
+0

我不能使用ApplicationRef對象,因爲'loadNextToLocation'功能只接受的typeof'ElementRef'object。 – Kliment

+2

'let element:ElementRef = this.app ['_ rootComponents'] [0] .location;' – ps2goat

+0

謝謝。這解決了我的問題 – Kliment

1

的問題是,讓根ElementRef,您的應用程序應當自舉。在某些情況下(讓服務中的ElementRef)我們應該等待。 我的解決方案:

import {Injectable, ApplicationRef, ElementRef} from 'angular2/core'; 

@Injectable() 
export class SomeService { 
    private _appElementRef: ElementRef; 

    constructor(appRef: ApplicationRef) { 
    appRef.registerBootstrapListener(appComponentRef => { 
     this._appElementRef = appComponentRef.location; 
    }); 
    } 
}