Ngx-bootstrap的无线电组在加载时不会绑定到所选值

时间:2019-07-31 04:13:09

标签: angular angular-ngmodel ngx-bootstrap

我的ngx-bootstrap单选按钮可以正常工作并绑定到selectedValue,除非首次加载页面时。尽管selectedValue已初始化,但是ngModel在首次加载页面时不会绑定到它。

我已经尝试在类和OnInit()中初始化selectedValue成员,希望这是一个操作顺序问题,但是ngModel在页面加载时仍然不会绑定。

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;
  }
}

这是我的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>

ngx-bootstrap演示可以正常工作,如所选的初始按钮所示。可能是ng-model不喜欢整数吗?

https://angular-je8xrf.stackblitz.io

1 个答案:

答案 0 :(得分:0)

尝试使用属性绑定([btnRadio]="value"

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

代替字符串插值(btnRadio="{{ value }}"

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

  

这是您推荐的Working Sample StackBlitz