3

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>

moreton
  • 31
  • 1
  • 1
  • 2

1 Answers1

6

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.

Community
  • 1
  • 1
Gregor Doroschenko
  • 11,488
  • 5
  • 25
  • 37
  • I agree that the first option is better, it is much clearer and very common, however I do not follow your argumentation. Could you please elaborate on 'so this element will be created in DOM. This is not so good by too much html elements. You page will be slow. ' Do you mean it in the way that first example appends element to DOM only if condition happens and second creates element first and if condition is met, then removes it from the DOM? I have not seen this in the docs. Where exactly is that described? Thanks. – Kristian Jan 29 '18 at 21:49
  • @Emocuc I updated my answer. So I hope it's enough to understand what i meant. – Gregor Doroschenko Jan 29 '18 at 22:09
  • 1
    oh, I must be real tired, I did not read the ng-container in your answer previously. The answer is sure clear now. Thanks. – Kristian Jan 29 '18 at 22:22