【问题标题】:Angular2: RadioButton change event is not bindingAngular2:单选按钮更改事件未绑定
【发布时间】:2016-10-21 04:57:49
【问题描述】:

在这里,我想简单地将 RadioButton 与更改事件绑定。不使用任何库。

以下工作正常。

<input type="radio" name="test" value="A" (change)="onPropertyChange('test')">
<input type="radio" name="test" value="B" (change)="onPropertyChange('test')">

但这个不是:

<div class="btn-group col-lg-2" data-toggle="buttons" >
<label *ngFor=" let app of applications; let i = index; " 
       class="btn btn-default " [ngClass]="{'active':( ticket.app == app)}">      
      <input type="radio" id="app{{i}}"  name="app" value="{{i}}"                   
           checked="{{ ( ticket.app == app ) ? 'checked' : ''}}" (change)=" 
           onPropertyChange('app')"  > 
     {{app}}
</label>
</div>

将更改事件绑定到标签时,它给了我旧值。

任何人都可以提出正确的方法吗?

【问题讨论】:

  • 在处理 Angular 时不应依赖 Bootstrap javascript。你的问题是data-toggle="buttons"
  • 添加onPropertyChange函数ts代码
  • change 事件仅在检查无线电时触发。在您的情况下,您将传递给函数onPropertyChange('app') 的值硬编码。您可能希望将其更改为 onPropertyChange(i)
  • 感谢@yurzui 提出正确的方法。很有帮助。

标签: javascript angular twitter-bootstrap-3 radio-button dom-events


【解决方案1】:

没有库的双向绑定:

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-default" [class.active]="yourVariable==item" (click)="yourVariable=item" *ngFor="let item of items">
        <input type="radio" style="display: none;" name="radios" [(ngModel)]="yourVariable" [value]="item" [checked]="yourVariable==item" />
        {{yourLabelText}}
    </label>
</div>

【讨论】:

    【解决方案2】:

    使用 ng2-bootstrap,

    <div class="btn-group col-lg-2">
        <label *ngFor="let app of applications" class="btn btn-default" [(ngModel)]="ticket.app" btnRadio="{{app}}">{{app}}</label>
    </div>
    

    在.ts文件中,

    • 已添加import { ButtonRadioDirective } from 'ng2-bootstrap/components/buttons';

    • @Component注解中,作为directives: [ButtonRadioDirective]传递。

    它工作正常。希望它对你有用。

    【讨论】:

      【解决方案3】:

      使用 Angular 2 RC2,不再需要创建 RadioButtonState:

      单选按钮现在可以共享 FormControl 实例

      <form #f="ngForm">
         <input type="radio" name="food" [(ngModel)]="food" value="chicken">
         <input type="radio" name="food" [(ngModel)]="food" value="fish">
      </form>
      

      还有:

      class MyComp {
         food = 'fish';
      }
      

      来源:5thingsangular - Issue #8

      【讨论】:

        猜你喜欢
        • 2015-10-31
        • 1970-01-01
        • 2019-04-06
        • 2017-03-02
        • 2014-12-18
        • 1970-01-01
        • 2017-08-20
        • 2016-10-10
        • 2014-05-12
        相关资源
        最近更新 更多