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