Daniel Fowler Daniel Fowler - 6 months ago 45
AngularJS Question

How can I have two ng-contents in the same template controlled by *ngIf

I have an angular 2 component for displaying a bootstrap 3 button group. The component can either have a label or it can stand alone.

My solution was to use two ng-contents controlled by an *ngIf however, it refuses to display either of the ng-contents and does not throw an error.

Here's btn-multi.html:

<div class="form-group"
*ngIf="label">
<label class="control-label col-lg-2 col-md-3">
{{ label }}
</label>

<div class="col-lg-10 col-md-9">
<div class="btn-group">
<ng-content></ng-content>
</div>
</div>
</div>

<div class="btn-group"
*ngIf="!label">
<ng-content></ng-content>
</div>


And here is how it is used:

<btn-multi label="Some Label"
[(value)]="someValue">
<btn [value]="true">Yes</btn>
<btn [value]="false">No</btn>
</btn-multi>


And this is it working with just the one ng-content:

enter image description here

I'm currently on angular 2 beta-15.

Thanks!

Answer

NgIf is getting in the way of including the content since ng-content is being rendered after NgIf is evaluated.

You need to take another approach on it, maybe something like this:

<div [ngClass]="{'form-group': label}">
  <label *ngIf="label" class="control-label col-lg-2 col-md-3">
    {{ label }}
  </label>

  <div [ngClass]="{'col-lg-10 col-md-9': label}">
    <div class="btn-group">
        <ng-content></ng-content>
    </div>
  </div>
</div>

And there are also even better ways to do it, it all depends on how you want this component to be consumed.

FYI, just did this on the fly so its not tested, but just to give you a general idea.