2016-12-01 25 views
2

このリンクを使用して、コンポーネントセットを動的にロードするディレクティブを作成しました。 - link 現在のViewContainerではなく親にコンポーネントを追加する必要があります。どのように私はこれを行うことができます誰も考えを持っていますか?Angular2親にコンポーネントを動的に追加します

背景 - コンポーネントをブートストラップモードで動的にロードしています。オーバーフローが非表示に設定されているので、コンポーネントがカットされています。だから私はモーダルの外側にコンポーネントを置く必要があります。ここで

は私が(動的にロードされる)コンポーネントは常に私はコンテナまたは親としてそれを使用したいコンポーネントの後に追加されていることと同じ混乱を持っているディレクティブ

import { 
    ComponentFactory, ComponentFactoryResolver, ComponentRef, 
    Directive, ElementRef, EventEmitter, 
    HostListener, Input, Output, Renderer, 
    ViewContainerRef 
} from '@angular/core'; 

import { AutoCompleteComponent } from './auto-complete.component'; 

import { AutoComplete } from './auto-complete.model'; 
import { Contact } from './contact.model'; 

@Directive({ 
    selector: '[AutoComplete]' 
}) 
export class AutoCompleteDirective { 

    autoCompleteComponentRef: ComponentRef<AutoCompleteComponent>; 

    @Output() onContactSelected = new EventEmitter<Contact>(); 

    constructor(
     private el: ElementRef, 
     private viewContainer: ViewContainerRef, 
     private componentFactoryResolver: ComponentFactoryResolver, 
     private renderer: Renderer 
    ) { 
    } 

    @HostListener('keyup') onKeyUp() { 
     this.search(); 
    } 

    private search() 
    { 
     if (this.autoCompleteComponentRef == undefined) { 
      let autoCompleteComponentFactory = this.componentFactoryResolver.resolveComponentFactory(AutoCompleteComponent); 
      this.autoCompleteComponentRef = this.viewContainer.createComponent(autoCompleteComponentFactory); 


      this.autoCompleteComponentRef.instance.onBusinessContactSelected.subscribe((x) => { 
       this.onContactSelected.emit(x); 
      }) 
     } 
     this.autoCompleteComponentRef.instance.search(this.forename, this.surname); 

    } 

} 
+0

モーダルでプランナーを提供できますか? – yurzui

+0

基本的にターゲットに追加したい場合 – Demodave

答えて

0

ためのコードです。これは設計としてのバグか機能ですか?

+0

コンストラクタに挿入されたviewContainerの代わりに@ViewChildを使用する例が見つかりました。この例では、親には 'target'(div要素)というビューの子があります。ターゲットはアンカーとして使用されます。コンポーネントを親コンポーネントの "in"に追加するようにすると、コンポーネントは後に追加できます。それが助けて欲しい。リンク:http://plnkr.co/edit/UGzoPTCHlXKWrn4p8gd1 – Rekoolno

関連する問題