javascript - 监听指令内的取消选中事件

标签 javascript angular listener angular2-directives

我的 radio 输入有指令。我想收听此输​​入的检查和取消检查(通过检查其他 radio 暗示)事件。

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

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

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

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

编辑:

这是一个plunker这说明了问题...只有选定的 radio 应显示为红色

最佳答案

我的方法是:

  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 属性属于该指令,并且我们将其绑定(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');
    }
}

Live Demo

关于javascript - 监听指令内的取消选中事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44813858/

相关文章:

java - 用于检测变量值变化的更改监听器的替代方案

javascript - 如何从对象中检索数据并将其存储到数组中

javascript - 使用 iframe 构建的 Access Dom

javascript - 对模糊的操作,除非通过 react 单击特定元素或如何获取单击元素 onBlur

javascript - Angular2 的简单运行会引发 es6-promise .Promise 错误

angular - 在 Angular CLI 中生成的 Git

Angular 被动事件监听器

java - 如何删除用作监听器的 lambda 表达式/方法句柄?

jQuery:我使用什么监听器来检查浏览器自动填充密码输入字段?

javascript - 使用 ng-hide 通过 colResizable 切换表中的列