问题
I could just do
<my-awesome-component *ngIf="ConditionToIncludeComponent"></my-awesome-component>
But every document on inserting component in dom dynamically is based on ViewContainerRef. I like what it does. But what makes it so special over *ngif?
Just point out pros and cons of both. Please. Thanks!
回答1:
TLDR;
If you don't know what component will be used in a component template when putting together this template use viewContainerRef
. If you do know the component beforehand but it can sometimes be hidden, use ngIf
.
Explanation
ViewContainerRef
is used to specify the insertion point of the dynamic component. When using ngIf
you need to specify the component in html
in advance. So if you have a spot where you will insert one of three components you will need to do the following:
<my-awesome-component1 *ngIf="ConditionToIncludeComponent1"></my-awesome-component1>
<my-awesome-component2 *ngIf="ConditionToIncludeComponent2"></my-awesome-component2>
<my-awesome-component3 *ngIf="ConditionToIncludeComponent3"></my-awesome-component3>
Whereas with viewContainerRef
you need only one spot (usually specified using `ng-container). Using ngComponentOutlet it can be done like this:
template: `<ng-container ngComponentOutlet="componentToInsert"></ng-container>`
class MyComponent {
const myAwesomeComponent1 = cfr.resolveComponentFactory(MyAwesomeComponent1);
const myAwesomeComponent2 = cfr.resolveComponentFactory(MyAwesomeComponent1);
const myAwesomeComponent3 = cfr.resolveComponentFactory(MyAwesomeComponent1);
if (ConditionToIncludeComponent1) {
componentToInsert = myAwesomeComponent1;
else if (ConditionToIncludeComponent2) {
componentToInsert = myAwesomeComponent2;
else if (ConditionToIncludeComponent3) {
componentToInsert = myAwesomeComponent3;
Or component manually using createComponent
method:
template: `<ng-container #spot></ng-container>`
class MyComponent {
@ViewChild('spot', {read: ViewContainerRef}) vc;
const myAwesomeComponent1 = cfr.resolveComponentFactory(MyAwesomeComponent1);
const myAwesomeComponent2 = cfr.resolveComponentFactory(MyAwesomeComponent1);
const myAwesomeComponent3 = cfr.resolveComponentFactory(MyAwesomeComponent1);
if (ConditionToIncludeComponent1) {
vc.createComponent(myAwesomeComponent1);
else if (ConditionToIncludeComponent2) {
vc.createComponent(myAwesomeComponent2);
else if (ConditionToIncludeComponent3) {
vc.createComponent(myAwesomeComponent3);
Besides inconvenience and a bloated html template the bigger problem with the ngIf
approach is performance impact since three ngIf
directives will have to perform some logic on each change detection cycle.
For more information read:
- Exploring Angular DOM manipulation techniques using ViewContainerRef
来源:https://stackoverflow.com/questions/46670125/why-use-viewcontainerref-over-ngif