2016-05-27 1 views
14

ComponentResolverとViewContainerRefを使用して動的なAngular 2コンポーネントを読み込むことができます。ComponentResolverを使用してAngular 2 Componentを動的に作成しながら入力を渡す

しかし、これに子コンポーネントの入力変数を渡す方法を理解できません。

parent.ts上記の例のように

@Component({ 
    selector: "parent", 
    template: "<div #childContainer ></div>" 
    }) 
    export class ParentComponent { 
     @ViewChild("childContainer", { read: ViewContainerRef }) childContainer: ViewContainerRef; 

     constructor(private viewContainer: ViewContainerRef, private _cr: ComponentResolver) {} 

     loadChild =(): void => { 
      this._cr.resolveComponent(Child1Component).then(cmpFactory => {    
       this.childContainer.createComponent(cmpFactory); 
      }); 
     } 
    } 

child1の

@Component({ 
    selector: "child1", 
    template: "<div>{{var1}}</div><button (click)='closeMenu()'>Close</button>" 
}) 
export class Child1Component { 
    @Input() var1: string; 
    @Output() close: EventEmitter<any> = new EventEmitter<any>(); 

    constructor() {} 

    closeMenu =(): void => { 
     this.close.emit(""); 
    } 
} 

loadChildは、ボタンのクリックで呼び出されていると言う、私はChild1Componentをロードすることができていますが、どのようにパスvar1子供の入力? はまた、どのように命令的にそれを渡すためにあなたが持っている@Output

答えて

26

飾らclose持つEventEmitterを購読する:出力のためのハンドラを登録して

loadChild(): void { 
    this._cr.resolveComponent(Child1Component).then(cmpFactory => {    
    let cmpRef = this.childContainer.createComponent(cmpFactory); 
    cmpRef.instance.var1 = someValue; 
    }); 
} 

も似ています。

loadChild(): void { 
    this._cr.resolveComponent(Child1Component).then(cmpFactory => {     
    let instance: any = this.childContainer.createComponent(cmpFactory).instance; 
    if (!!instance.close) { 
     // close is eventemitter decorated with @output 
     instance.close.subscribe(this.close); 
    } 
    }); 
} 

close =(): void => { 
    // do cleanup stuff.. 
    this.childContainer.clear(); 
} 
+0

でそれをやった方法ですと、 @Output関数の使い方も? –

+0

ありがとうございます。 –

+0

@Gunterは、あなたから提案されたのと同じ方法で試しましたが、ブラウザのコンソールでいくつかの例外が発生し、期待どおりに動作しません。この投稿に返信して助けてもらえますか? http://stackoverflow.com/questions/38360904/typeerror-cannot-read-property-createcomponent-of-undefined – Krishnan

3

これは私がこれのおかげで、私はコールバックを得ていないのですが、私はにcreateComponent上で直接インスタンスを取得しています、あなたが解決策を更新してくださいすることができアンギュラ2.2.3

let nodeElement = document.getElementById("test"); 
let compFactory = this.componentFactoryResolver.resolveComponentFactory(AnyCustomComponent); 
let component = compFactory.create(this.viewContainerRef.injector, null, nodeElement); 
// This is where you pass the @Input 
component.instance.anyInput = anyInput; 
関連する問題