Reputation:
A component about-me
is created dynamically and injected in a div
but the component is not rendered inside the div
tag instead rendered as a sibling. How to render the dynamically created component inside the div
tag.
Code:
home.component.html
<div class="card-content" #sectionContainer></div>
home.component.ts
...
@ViewChild('sectionContainer', {static: true, read: ViewContainerRef }) sectionEntry: ViewContainerRef;
...
loadAboutMeComponent() {
this.store.dispatch(new OpenSection());
this.sectionEntry.clear();
const factory = this.resolver.resolveComponentFactory(AboutmeComponent);
const componentRef = this.sectionEntry.createComponent(factory);
}
Console:
The component is rendering perfectly fine, but not inside the div. May i know why?
Upvotes: 2
Views: 490
Reputation: 11934
What's happening in your code is that by using { read: ViewContainerRef }
on a div
element you are basically transforming it into a ViewContainer
which, as its name implies, it is just a container for other views. A ViewContainer
it is not rendered on the page, it just displays the views that it contains.
You can read more about host views, embedded views and ViewContainer
's API here.
Here is the TLDR for the aforementioned article.
Of course, any element can server as a ViewContainer
, but usually you would want to use <ng-container #viewcontainer></ng-container>
.
So, if you want your component to be rendered inside the div, you'd have to do this:
<div class="card-content">
<ng-container #sectionContainer></ng-container>
</div>
Upvotes: 2