ページの最上部または本文要素でコンポーネントをインスタンス化したいと思います。from component by function<new-element>
を使用viewContainerRef
して<person>
コンポーネントを追加するとviewContainerRef.createComponent
、新しく作成された要素がホスト要素の直後に配置されます。
<app>
<persons>
<person>host</person>
<new-element>child</new-element>
</persons>
</app>
コンポーネントから要素の<new-element>
直後に作成する適切な方法はありますか?<app>
<person>
<app>
<new-element>child</new-element>
<persons>
<person>host</person>
</persons>
</app>
ターゲットViewContainerRef
をperson
コンポーネントに渡すことが可能であれば、それは機能するはずです。ng-container
コメント以外の要素をDOMに残さないを使用することをお勧めします。
export class AppComponent {
@ViewChild('target', { read: ViewContainerRef }) targetRef: ViewContainerRef;
}
<app>
<ng-container #target></ng-container>
<persons>
<!-- Pass the target in -->
<person [target]="targetRef">host</person>
</persons>
</app>
そして、person
コンポーネントで次のことを行います。
@Input('target') target: ViewContainerRef;
// ...
this.target.createComponent( ... )
編集:セレクターをレンダリングターゲットとして使用したいので、コンポーネントを作成してから移動することができます。
viewContainerRef.createComponent( ... )
// The new component has been rendered as a sibling, so grab it and move it
document.querySelector('body').appendChild(viewContainerRef.element.nativeElement.nextSibling);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加