Search code examples
angularangular-cliconventionangular-ng-if

Where to put the ngIf?


I have a question about the ngIf of Angular 2. I'm currently developing my first bigger Angular 2-App and I'm wondering about the best positioning of the ngIf. I think that there should be a certain consistency. This are the three options I can think of, regarding to load a child-component:

In a div of the parent-component:

<div id="parent-component-div" *ngIf="loadChildComponent">
  <app-child-component></app-child-component>
</div>

In a child-component-tag of the parent-component:

<div id="parent-component-div">
  <app-child-component *ngIf="loadChildComponent"></app-child-component>
</div>

In the child-component:

<!-- parent-component -->
<div id="parent-component-div">
      <app-child-component></app-child-component>
</div>

<!-- child-component -->
<div id="child-component-div" *ngIf="loadComponent">
      <!-- child-component logic -->
</div>

I personally, find my self following option one, but seeing advantages of option three. But what is the convention? Is there a convention?


Solution

  • This is of course highly subjective, but I believe that it should be put on the element that is shown or hidden based on some condition.

    <div id="parent-component-div">
      <app-child-component *ngIf="loadChildComponent"></app-child-component>
    </div>
    

    We then may assume that this part of html is a template. So if you put ngIf on an element itself and we know how structural ngIf directive is transformed we end up with this DOM:

    <div id="parent-component-div">
      <template [ngIf]="loadChildComponent">
          <app-child-component></app-child-component>
      </template>
    </div>
    

    which makes sense. If you put ngIf on the parent div like this:

    <div id="parent-component-div" *ngIf="loadChildComponent">
      <app-child-component></app-child-component>
    </div>
    

    parent-component-div becomes part of a template and it doesn't seem like what you want to do.

    The third option seems the least right for me since a component shouldn't care whether it's shown or not. If it's shown, then it should proceed with it's functionality.