I have 4 angular elements (Web Components) in my projects. I have added script tag for those web components in index.html <script src="web-angular-element.js"> </script>
and i want to display those elements dynamically in my angular application. i am just using the components selector to display that in application and name of selector is coming from the service like this `' based on the user access.
<div class="widgets-section" *ngFor="let widgets of userWidget">
<div class="wt">
<h3>{{widgets.name}}</h3>
</div>
<div class="wb">
{{widgets.code}}
</div>
<div class="wf">
<button class="button-standard">{{widgets.text}}</button>
</div>
</div>
Here widget code is widgets.code = <component-name></component-name>
that is not working even i have tried the "ngTemplateOutlet"
<ng-container *ngTemplateOutlet="widgets.code"></ng-container>
<ng-template #abc>
<component-name></component-name>
</ng-template>
Here i am passing widget code is widgets.code = "abc"
and based on the code i am trying to render the component
You should bind ngTemplateOutlet
to a variable that is a TemplateRef
.
This simple code below is not a full solution for your issue, but it will give you the solution for dynamic components. What is left for you to do is to get the correct TemplateRef
by the widget.code
.
HTML:
<ng-container *ngTemplateOutlet="carrentTemplate"></ng-container>
<ng-template #abc>
<component-name></component-name>
</ng-template>
<ng-template #def>
<component-name-2></component-name-2>
</ng-template>
TS:
carrentTemplate: TemplateRef<any>;
@ViewChild('abc') abc: TemplateRef<any>;
@ViewChild('def') def: TemplateRef<any>;
ngOnInit() {
if (true) { // some condition
this.currentTemplate = this.abc;
} else {
this.currentTemplate = this.def;
}
}