【问题标题】:Listen to uncheck event inside directive监听指令内的取消选中事件
【发布时间】:2017-06-28 23:02:44
【问题描述】:

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

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

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

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

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

编辑:

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

【问题讨论】:

  • 请添加一些上下文:让我们看看指令周围的模板。单选按钮是否在表单中?您是在使用模板驱动的表单还是响应式表单等...
  • 为什么不监视单选按钮影响的属性状态而不是按钮本身的状态?
  • @BeetleJuice 无线电输入是一种形式,我正在使用反应形式......我不明白它如何帮助解决问题,但如果你认为你可能只能提供帮助知道这些信息,我将非常乐意回答您的所有问题!
  • @Claies 你所说的财产状况是什么意思?你说的是什么属性?
  • 请在收音机输入框周围显示表单模板

标签: javascript angular listener angular2-directives


【解决方案1】:

我的做法是:

  1. 将拥有单选按钮的FormControl 注入指令中。
  2. 在指令中,订阅控件的valueChanges observable,以便在控件的值更改时收到通知
  3. 每次值更改时,根据 FormControl 的新值是否匹配此特定单选按钮的 value 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多