0

I have a scenario where I have a component which does some http requests to show data and if there is an exception while doing so, I want to show instead just the error component.

Does it make sense to have the error component already on the template as

<ng-template [ngIf]="showError">
    <error-view></error-view>
</ng-template>

and set the flag to true to show.

Or inject the component dynamically using ComponentFactoryResolver once there is error?

Saksham
  • 9,037
  • 7
  • 45
  • 73
  • ComponentFactoryResolver would be an overkill for most of the cases. Using conditional rendering with ngIf is fair and better intuitive. – talhature Sep 02 '20 at 10:58

1 Answers1

0

The *ngIf directive doesn't immediately render the elements.

The following

<ng-template [ngIf]="showError">
  <error-view></error-view>
</ng-template>

or the shorter variant

<error-view *ngIf="showError"></error-view>

doesn't actually render the component until the showError is true.

During the rendering, the ng-template would be replaced with a diagnostic comment like

<!--bindings={
  "ng-reflect-ng-if": "false"
}-->

So I'd say using ComponentFactoryResolver is unnecessary in this situation.

ruth
  • 29,535
  • 4
  • 30
  • 57