4

I am trying to inject component dynamically based on the value selected by the user in a dropdown.

My requirement is that whenever a user changes the value of drop-down and click on view component gets injected but again if the user changes the dropdown value and clicks on view same injected component should be re-rendered but instead one new component gets injected.

Is there any way we can achieve this.

Note: on dropdown change, a service is called and different data will be returned from the server.

Stackblitz for the issue: https://stackblitz.com/edit/angular-cszxfs?file=src%2Fapp%2Fapp.component.ts

Thanks in advance

10
  • What the heck is a "refreshed" component? Commented Jan 18, 2019 at 13:28
  • @cgTag I mean to say that component should be re-rendered with new data Commented Jan 18, 2019 at 13:29
  • @cgTag edited my post Commented Jan 18, 2019 at 13:30
  • You have to use a service with observables and emit new values that the component subscribes to. Updating the data for a component has nothing to do with using component factories. Since the component can not have input binding you have to figure out how to send it data on your own. Commented Jan 18, 2019 at 13:34
  • why do you need to inject dynamically a component based on the value of the droprown? A ngIf or hide property doesn't do the work? Commented Jan 18, 2019 at 13:36

2 Answers 2

1

So first I am removing the components and then adding it back in the view:

here goes my code:

 renderTreeListReport(element: string) {
   this.removeComponents();
   const component = resultComponent[element];
   const factory = this.resolver.resolveComponentFactory<any>(component);
   this.component = this.resultcontainer.createComponent(factory);
   this.components.push(this.component);//for tracking the components created
   this.component.instance.config = this.config;
   this.component.instance.pagingInfo = this.pageble;
 }


 public removeComponents() {
   const components = this.components;
   if (components.length > 0) {
     components.forEach(comp => {
       this.resultcontainer.remove(components[comp])
     })
   }
 }
Sign up to request clarification or add additional context in comments.

Comments

-1
<div *ngIf="somecondition">
<app-componentOne></app-componentOne>
</div>

<div *ngIf="somecondition">
<app-componentTwo></app-componentTwo>
</div>

like that you can import more that one component on selection of dropdown in ng if just manage your condition if that is true accordingly component will display..

1 Comment

Thanks for replying but this is not what I am looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.