监听指令中的取消选中事件

Listen to uncheck event inside directive

我有一个关于我的无线电输入的指令。我想听听这个输入的检查和取消检查(通过检查其他无线电暗示)事件。

我已尝试将此添加到我的指令中:

@HostListener('change') onChange(): void {
    console.log('change');
}

但是当我的输入被取消选中时,更改事件不会被触发。

有没有办法监听checked属性?如果没有,你有什么建议?

编辑:

这里有一个 plunker 来演示这个问题...只有选定的收音机应该显示为红色

我的方法是:

  1. 将拥有单选按钮的 FormControl 注入到指令中。
  2. 在指令中,订阅控件的 valueChanges 可观察对象,以便在控件的值更改时得到通知
  3. 每次值更改时,根据 FormControl 的新值是否与此特定单选按钮的值匹配 DOM 属性[,设置或删除所需的 CSS

修改模板

<input... selected [control]="form.get('checkbox')"...value='1'/>
<input... selected [control]="form.get('checkbox')"...value='2'/>

请注意 control 属性 属于该指令,并且我们将其绑定到我们感兴趣的 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');
    }
}

Live Demo