(更改)当选中其他单选按钮时

时间:2019-09-02 12:33:25

标签: html angular

我有两个单选按钮,当按钮B被选中/未选中时,我需要触发一个事件。我无法将任何事件绑定到A。

<input type="radio" id="A" name="radiogrp" value="A">
<label for="A">A</label>
<input type="radio" id="B" name="radiogrp" value="B" (change)="showOrHideElement()">
<label for="B">B</label>

仅当按钮B被选中时它才起作用,当我单击另一个按钮时不会触发该事件。 如何在不绑定任何内容的情况下收听B的按钮更改?

1 个答案:

答案 0 :(得分:0)

每次使用值更改log()时,都可以在使用ngModel时使用ngModelChange。

<input type="radio" id="A" name="radiogrp" value="A" [(ngModel)]="radioValue" (ngModelChange)="log()">
<label for="A">A</label>
<input type="radio" id="B" name="radiogrp" value="B"[(ngModel)]="radioValue" (ngModelChange)="log()" >
<label for="B">B</label>

demo ??

如果要在选择B的情况下运行该方法,则可以将事件绑定到B元素

<input type="radio" id="A" name="radiogrp" value="A" [(ngModel)]="radioValue" >
<label for="A">A</label>
<input type="radio" id="B" name="radiogrp" value="B"[(ngModel)]="radioValue" (ngModelChange)="log()" >
<label for="B">B</label>

demo ??

您还可以使用Form Control

作为其他示例,使用反应形式
<input type="radio" id="A" name="radiogrp" value="A" [formControl]="selection">
<label for="A">A</label>
<input type="radio" id="B" name="radiogrp" value="B" [formControl]="selection" >
<label for="B">B</label>

组件

  selection= new FormControl('A')

  ngOnInit(){
      this.selection.valueChanges.subscribe(value =>{

        if (value == 'B') {
        console.log(`B is selected ? `,value)
        } else {

        console.log(`B is not selected ? `,value)
        }
      })
  }

demo ??