我的 radio 输入有指令。我想收听此输入的检查和取消检查(通过检查其他 radio 暗示)事件。
我尝试将其添加到我的指令中:
@HostListener('change') onChange(): void {
console.log('change');
}
但是当我的输入未被选中时,更改事件不会被触发。
有没有办法监听checked
属性?如果没有,你有什么建议?
编辑:
这是一个plunker这说明了问题...只有选定的 radio 应显示为红色
最佳答案
我的方法是:
- 将拥有单选按钮的
FormControl
插入指令中。 - 在指令中,订阅控件的
valueChanges
可观察对象,以便在控件的值更改时收到通知 - 每次值更改时,根据
FormControl
的新值是否与此特定单选按钮的值 DOM 属性匹配来设置或删除所需的 CSS
修改后的模板
<input... selected [control]="form.get('checkbox')"...value='1'/>
<input... selected [control]="form.get('checkbox')"...value='2'/>
请注意,control
属性属于该指令,并且我们将其绑定(bind)到我们感兴趣的 FormControl
的特定实例
修改后的选定指令
@Directive({selector: 'input[selected]'})
export class Selected implements OnChanges {
constructor(private element:ElementRef) {}
//instance of FormControl this radio btn belongs to
@Input() control:FormControl;
//Once a FormControl is bound, start listening to its changes
//Once a change occurs, call manageClass and provide it the new value
ngOnChanges(){
this.control.valueChanges.subscribe(newVal=>this.manageClass(newVal));
}
//Compares the new value to the "value" property of the DOM radio btn
//If they match, it means the radio btn is currently selected.
// Add or remove the CSS class as appropriate
manageClass(newVal){
let e = this.element.nativeElement;
if(e.value===newVal) e.parentElement.classList.add('selected');
else e.parentElement.classList.remove('selected');
}
}
关于javascript - 监听指令内的取消选中事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44813858/