Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Below I have created a dynamic component

AppComponent.html

HTML
<input type="button" value="One" (click)="setVal('one')">
<input type="button" value="Two" (click)="setVal('two')">
<br>
<app-dynamic-component [key]="keyvalue"></app-dynamic-component>


AppComponent.ts

JavaScript
keyvalue = 'one'

setVal(val) {
    this.keyvalue = val;
}


and its logs the following:

Console log here


----------


And following are using `*ngIf`

AppComponent.html

HTML
<input type="button" value="One" (click)="setVal('one')">
<input type="button" value="Two" (click)="setVal('two')">
<br>
<app-component-one *ngIf="keyvalue=='one'"></app-component-one>
<app-component-two *ngIf="keyvalue=='two'"></app-component-two>


AppComponent.ts

JavaScript
keyvalue = 'one'

setVal(val) {
    this.keyvalue = val;
}


and the logs:

Console log here


----------

Both does the same thing of creating and destroying the child components. What is the advantage of using ComponentFactoryResolver over *ngIf and lets say *ngIf gets the job done, should I use ComponentFactoryResolver instead?

What I have tried:

Implemented both, but I am confused about which is the better way.
Posted
Updated 2-Jul-18 3:50am

1 solution

Using ComponentFactoryResolver for such a simple case is overkill. At least you should declare your worker components (one and two) as EntryComponents to be able to construct them dynamically.

ComponentFactoryResolver may be useful when you want to create a component from directive for example. The directive has no template so you cannot *ngIf the component and the only way is to use ComponentFactoryResolver.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900