我有两个单选按钮,当按钮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的按钮更改?
答案 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>
如果要在选择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>
您还可以使用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)
}
})
}