moreton
moreton

Reputation: 31

Should I use Angular ngIf directly on component

I'm new to Angular and getting used to the basics.

If I have a component that I want to show or hide depending on a variable should I have the *ngIf on the component itself or the contents inside the component.

Eg.1 The Component 'photos' component will load if the variable photos is true

<photos *ngIf="photos"></photos>

Eg.2 Contents of the component The photos component is always there but the contents are loaded

<section class="photos-content" *ngIf="photos"> // content here </section>

Upvotes: 3

Views: 16810

Answers (1)

Gregor Doroschenko
Gregor Doroschenko

Reputation: 11696

If you are using *ngIfdirective on html elements (eg. 2), so this element will be created in DOM. This is not so good by too much html elements. You page will be slow. So the first example (eg. 1) is better.

Otherwise you can extend your second example by using <ng-container></ng-container> like this:

<ng-container *ngIf="photos">
  <section class="photos-content">
    // content here
  </section>
</ng-container>

ng-container isn't displayed in DOM.

More explonation about ng-container you can find on this good answer and here is a short summary:

<ng-container> is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.

<ng-container> is rendered as an HTML comment.

Here is an example

This angular code:

<div>
    <ng-container>fooText</ng-container>
<div>

will produce this comment in your html file:

<div>
    <!--template bindings={}-->fooText
<div>

Read more about ng-container here.

Upvotes: 6

Related Questions