私のページの1つにコンポーネントを動的に追加/削除するコードがあります。それはうまくいくと思われ、私はRob Wormaldの素晴らしい方法Ng2 Advanced Talkに基づいています。その標準的な方法で物事を行うngIf内でコンポーネントを動的に追加する
は次のようになります。
@Component({
template: `
<parent-component>
<template #dyn_target></template>
</parent-component>
`
})
export class MyComp {
@ViewChild('dyn_target', {read: ViewContainerRef}) myTarget;
constructor(protected cfr: ComponentFactoryResolver) {}
ngOnInit(): void {
const factory = this.cfr.resolveComponentFactory(DynComp);
const compRef = this.myTarget.createComponent(factory);
}
}
すべてが幸せであると動作します。しかし今、私の質問は、コンポーネントのターゲットの場所が* ngIfの内部にある要素の場合、どうすればこのようなことをするのですか? * ngIfが新しい要素を表示するべき時を知っているコードがありますが、* ngIf内のターゲットのViewContainerRefを検索する方法がわかりません。
@Component({
template: `
<parent-component>
<other-comp></other-comp>
<div *ngIf="showMe"
<nested-comp>
<template #dyn_target></template>
</nested-comp>
</div>
</parent-component>
`
})
export class MyComp {
@ViewChild('dyn_target', {read: ViewContainerRef}) myTarget;
showMe: boolean = false;
constructor(protected cfr: ComponentFactoryResolver) {}
addDynComponent(): void {
// Q: how do I do this? vv
const target: ViewContainerRef = lookup('dyn_target');
const factory = this.cfr.resolveComponentFactory(DynComp);
const compRef = target.createComponent(factory);
}
}
私はほとんどのコンテンツが静的であるため、追加する必要があるただ一つのサブコンポーネントがあるngIfを削除し、ブロック全体を動的に、それは本当に私の場合は動作しませんしようと考えましたngIfが真であるとき/
ngIfがDOMに他の要素を追加した後で、ViewContainerRefをその場で見つける方法を知っている人は誰ですか?
注:別の方法として、コンポーネントクラスタイプの入力に基づいてネストされたコンポーネントを表示する新しいコンポーネントタイプを追加する方法を考えました。私はこのタイプのものがイオン2のために行われたことを見ており、おそらく私の場合はうまくいくかもしれませんが、過剰なもののようです。だから、何かのように:
@Component({
template: `
<parent-component>
<other-comp></other-comp>
<div *ngIf="showMe"
<nested-comp>
<show-comp [compClass]="dynClass"></show-comp>
</nested-comp>
</div>
</parent-component>
`
})
export class MyComp {
dynClass: any;
showMe: boolean = false;
addDynComponent(): void {
dynClass = DynComp;
}
}
右動作するはずだと思います。ありがとう。 –
@ViewChildrenプロパティデコレータを使用せずに直接ビュークエリを実行する方法はありますか? ViewChildrenがこのクエリを実行するために呼び出すコードを見つけようとしていますが、多くの運がなかったのです。 :( – Allen
私はそれがコンパイラの一部だと思います。 –