简体   繁体   中英

How do I add Angular Components before or after DOM elements in the template?

I want to use Angular ViewContainerRef createComponent method to dynamically create a component and add it to the view at a particular index (before or after). If I use viewContainerRef.createComponent and provide an index of 0, the component is added after any static DOM elements in the template.

In this example I would expect the component to be added before the "Template Div" element, but instead it is added after. Components added after that are added at the correct index, but never before the static DOM element.

https://stackblitz.com/edit/angular-dynamic-components-example-n6tae1?file=src/app/app.component.ts

Welcome to Stackoverflow. Regarding your question,

ViewContainerRef represents a container where one or more Views can be attached. The container can contain two kinds of Views, host views (created by instantiating a component with the createComponent() method), and embedded views (created by instantiating a TemplateRef with the createEmbeddedView() method).

Reference: https://angular.io/api/core/ViewContainerRef#description

In other words, when you use @ViewChild("container", { read: ViewContainerRef }) viewContainerRef: ViewContainerRef; you are referring to <div #container></div> as a ViewContainerRef which only contains host views and embedded views (both created dynamically). The static elements inside the div are not views of the ViewContainerRef, so when you use createComponent (method that creates a host view) passing a index as a second param, that index is related to the collection of views contained by ViewContainerRef (which excludes the static elements, and only includes host and embedded views).

Update

A workaround to get what you want is doing something like this

    <div id="main">     
    <div #containerBeforeTemplate></div>    
    <div>Template Div</div>     
    <div #containerAfterTemplate></div> 
    </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM