Javascript Angular 2 单选按钮事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37541106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:26:51  来源:igfitidea点击:

Angular 2 radio button events

javascripthtmlcssdomangular

提问by Tuomas Toivonen

What are those events called in Angular 2 when radio button is selected or unselected.

选择或未选择单选按钮时,在角2中调用的事件是什么。

Something like

就像是

<input type="radio" (select)="selected()" (unselect)="unselected()" />

So when I click one radio button in a group, it will fire selected()for the new selection and unselected()for the previous selection.

因此,当我单击一组中的一个单选按钮时,它将selected()为新选择和unselected()先前选择触发。

回答by Edmond Wang

It works,

有用,

<input type="radio" (change)="handleChange($event)" />

But you need code more to judge 'selected' or 'unselected'.
You may try this in your *.ts file:

但是您需要更多代码来判断“已选择”或“未选择”。
你可以在你的 *.ts 文件中试试这个:

  export class Comp {

    private _prevSelected: any;

    handleChange(evt) {
      var target = evt.target;
      if (target.checked) {
        doSelected(target);
        this._prevSelected = target;
      } else {
        doUnSelected(this._prevSelected)
      }
    }

  }

回答by edu

It works when you assign the click event to the label, instead of the input.

当您将点击事件分配给标签而不是输入时,它会起作用。

回答by user1632871

The html is like

html就像

 <div *ngFor = " let displayParameter of displayParameters" >    
    <!-- <li><a href="#">{{displayParameter}}</a></li>     -->
    <!-- <input type="radio"  name="displayParameter"  (change) ="handleChange(event)")>  -->
    <h5><input type="radio" name="radiogroup" (change)="handleChange(displayParameter)" [checked]="(idx === 0)" >{{displayParameter}} </h5>
</div>

and code is like

和代码就像

 handleChange(evt){ 
            this.displayParameter = evt;
        console.log(evt);
      }