Search code examples
angulartypescriptng-bootstrap

Ng bootstrap radio buttons


I am using NG-Bootstrap radio buttons like this

<div class="btn-group btn-group-toggle" ngbRadioGroup name="radioBasic" formControlName="model">
  <label ngbButtonLabel class="btn-primary">
    <input ngbButton type="radio" [value]="1"> Left (pre-checked)
  </label>
  <label ngbButtonLabel class="btn-primary">
    <input ngbButton type="radio" [value]="2"> Middle
  </label>
  <label ngbButtonLabel class="btn-primary">
    <input ngbButton type="radio" [value]="3"> Right
  </label>
</div>

And in compoment

this.radioGroupForm = this.formBuilder.group({
  'model': 1,
});

It is working OK, because all button are in one line, but what if I need different html that third button will be on another place in html, i have tried something like this

<div class="btn-group btn-group-toggle" ngbRadioGroup name="radioBasic" formControlName="model">
   <label ngbButtonLabel class="btn-primary">
      <input ngbButton type="radio" [value]="1"> Left (pre-checked)
   </label>
   <label ngbButtonLabel class="btn-primary">
      <input ngbButton type="radio" [value]="2"> Middle
   </label>
</div>

<div class="row">
   <div class="btn-group btn-group-toggle" ngbRadioGroup name="radioBasic" formControlName="model">
      <label ngbButtonLabel class="btn-primary">
        <input ngbButton type="radio" [value]="3"> Right
      </label>
   </div>
</div>

But it does not work, does it need to be wrapped in a group??


Solution

  • Looking into the source code of the ngbRadioGroup, I believe you guess is right - we need to wrap a group. I would expect we can use ng-container to avoid addition HTML:

    <ng-container ngbRadioGroup name="radioBasic" formControlName="model">
        <div class="btn-group btn-group-toggle" >
           <label ngbButtonLabel class="btn-primary">
              <input ngbButton type="radio" [value]="1"> Left (pre-checked)
           </label>
           <label ngbButtonLabel class="btn-primary">
              <input ngbButton type="radio" [value]="2"> Middle
           </label>
        </div>
        
        <div class="row">
           <div class="btn-group btn-group-toggle">
              <label ngbButtonLabel class="btn-primary">
                <input ngbButton type="radio" [value]="3"> Right
              </label>
           </div>
        </div>
    </ng-container>