Search code examples
angulardata-binding2-way-object-databinding

Angular 2: buttons data binding NgModel


I am trying to bind some group radio buttons with NgModel and take their values inside my component. The problem is that when I use 'data-toggle="buttons"' I cannot catch the click or change event. How can I solve this problem?

enter image description here

<div class="col-md-6">
<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-default active">
    <input type="radio" [(ngModel)]="period" (click)="dec()" value="yesterday" name="options" id="option1" autocomplete="off" checked> Yestedray
  </label>
  <label class="btn btn-default">
    <input type="radio" [(ngModel)]="period" value="today" name="options" id="option2" autocomplete="off"> Today
  </label>
  <label class="btn btn-default">
    <input type="radio" [(ngModel)]="period" value="currentMonth" name="options" id="option3" autocomplete="off"> January
  </label>
  <label class="btn btn-default">
    <input type="radio" [(ngModel)]="period" value="last6Months" name="options" id="option3" autocomplete="off"> Last 6 Months
  </label>
  <label class="btn btn-default">
    <input type="radio" [(ngModel)]="period" value="lastYear" name="options" id="option3" autocomplete="off"> Last Year
  </label>
</div>


Solution

  • You can get rid of data-toggle attr here.

    <label class="btn btn-default" [class.active]='period === "yesterday"'>
        <input type="radio" [(ngModel)]="period" value="yesterday" name="options" id="option1" autocomplete="off" checked> Yestedray
    </label>
    

    Also you can you ReactiveForms and subscribe to valueChanges.