Search code examples
angularangular-ngmodelngx-bootstrap

Ngx-bootstrap's radio group wont bind to selected value on load


My ngx-bootstrap radio buttons work fine and bind to selectedValue, except when the page first loads. Although selectedValue is initialized, ngModel will not bind to it when the page is first loaded.

I've tried to initialize selectedValue member in both the class and in OnInit(), hoping it was an order of operation issue, but ngModel still will not bind when the page loads.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'demo-buttons-radio',
  templateUrl: './radio.html'
})
export class DemoButtonsRadioComponent implements OnInit {
  radioModel = 'Left';

  selectedValue: number = 0;

  familyValues: number[] = [ 0, 1, 2, 3, 4 ];

  ngOnInit() {
    this.selectedValue = 0;
  }
}

Here's my HTML:

<pre class="card card-block card-header">{{selectedValue || 'null'}}</pre>
<div class="btn-group">
       <label class="btn btn-primary" [(ngModel)]="selectedValue" btnRadio="0" tabindex="0" role="button">0</label>
       <label class="btn btn-primary" [(ngModel)]="selectedValue" btnRadio="1" tabindex="0" role="button">1</label>
       <label class="btn btn-primary" [(ngModel)]="selectedValue" btnRadio="2" tabindex="0" role="button">2</label>
       <label class="btn btn-primary" [(ngModel)]="selectedValue" btnRadio="3" tabindex="0" role="button">3</label>
       <label class="btn btn-primary" [(ngModel)]="selectedValue" btnRadio="4" tabindex="0" role="button">4</label>
</div>


<div class="btn-group" *ngFor="let value of familyValues;" btnRadioGroup [(ngModel)]="selectedValue">
       <label class="btn btn-success" btnRadio="{{value}}" tabindex="0" role="button">{{value}}</label>
</div>

The ngx-bootstrap demo works, as shown by the initial button selected. Could it be that ng-model doesn't like integers?

https://angular-je8xrf.stackblitz.io


Solution

  • Try using attribute binding([btnRadio]="value")

    <label 
      class="btn btn-primary" 
      [(ngModel)]="selectedValue" 
      [btnRadio]="value" 
      tabindex="0"
      role="button">
      {{value}}
    </label>
    

    Instead of string interpolation(btnRadio="{{ value }}")

    <label 
      class="btn btn-primary" 
      [(ngModel)]="selectedValue" 
      btnRadio="{{value}}" 
      tabindex="0"
      role="button">
      {{ value }}
    </label>
    

    Here's a Working Sample StackBlitz for your ref.