2016-06-28 46 views
3

我用viewContainerRef.createComponent加載動態組件到根組件(.....),但實際其追加錯了地方,Angular2 viewContainerRef.createComponent正常工作

enter image description here

我的代碼:

----- ----- app.compoment.ts

export class AppComponent { 
    private viewContainerRef:ViewContainerRef; 
    public constructor(viewContainerRef:ViewContainerRef) { 
    this.viewContainerRef = viewContainerRef; 
    } 
} 

----- a.service.ts ------

@Injectable() 
export class ModalService { 
    private viewContainerRef:ViewContainerRef; 
    constructor(applicationRef: ApplicationRef, injector: Injector,private compiler: ComponentResolver) { 
     var classOfRootComponent = applicationRef.componentTypes[0]; 
     // this is an instance of application bootstrap component 
     var appInstance = injector.get(classOfRootComponent); 
     this.viewContainerRef= appInstance.viewContainerRef; 
    } 
    alert() {console.log(this.viewContainerRef); 
     this.compiler.resolveComponent(ModalComponent) 
     .then(
      (factory) => 
      this.viewContainerRef.createComponent(factory, 0, this.viewContainerRef.injector) 
     ).then((componentRef) => { 
       return componentRef; 
      } 
     ); 
    } 
} 

回答

4

這是「按設計」。如果你想<custom-modal>裏面<my-app>插入添加一個目標元素進入<my-app>模板,並以此作爲目標又見討論https://github.com/angular/angular/issues/9035

您需要從AppComponent傳遞到ModalService

@Component({ 
    selector: 'my-app', 
    template: `<div #target></div>` 
}) 
export class AppComponent { 
    @ViewChild('target', {read: ViewContainerRef}) viewContainerRef:ViewContainerRef; 

    constructor(private modalService:ModalService) {} 

    ngAfterViewInit() { 
    this.modalService.viewContainerRef = this.viewContainerRef; 
    } 
} 

這PR是有關類似的使用案例和您可能感興趣的https://github.com/angular/angular/pull/9393

+0

THKS回覆!我不熟悉stackoverflow。我不會在根組件中注入ModalService,我想知道我已經在ModalService中獲得了ViewContainerRef,但爲什麼無法獲得它的注入? – phevose

+0

我真的不明白你的問題。您從根組件獲得'ViewContainerRef',並添加到它將創建'ViewContainerRef'的兄弟。如果你想在根元素中添加,你需要在根元素模板中的一個元素的'ViewContainerRef'。我的答案顯示瞭如何獲得這樣的'ViewContainerRef'。 –

+0

換句話說,我可以從根的viewContainerRef服務中獲取第一個孩子(my-app)ViewContainerRef嗎?因爲我不想污染根組件(除了設置this.viewContainerRef)。 – phevose