且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

angular2复选框formcontrol

更新时间:2023-10-15 08:58:10

我相信我通过利用覆盖"默认CheckboxControlValueAccessor的自定义指令解决了您(和我)的问题. Angular2核心将onChange事件设置为触发该框,无论是否选中该框.下面的代码使用其是否被选中以及其值触发一个对象.您只需要将html元素设置为类型复选框的输入,并使用[value] = {valueToTrack}

I believe I solved your (and my) issue by utilizing a custom directive that "overrides" the default CheckboxControlValueAccessor. Angular2 core sets the onChange event to fire whether the box is checked or not. The code below fires an object with the whether it's checked and the value. You will just need to set the html element as an input of type checkbox, and attached the value you want to track with [value]={valueToTrack}

import {Directive, ElementRef, Renderer, forwardRef} from '@angular/core';

import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';


export const CHECKBOX_VALUE_OVERRIDE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => CheckboxControlValueOverrideAccessor),
  multi: true,
};

@Directive({
  selector: 'input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]',
  host: {'(change)': 'onChange({checked: $event.target.checked, value: $event.target.value})', '(blur)': 'onTouched()'},
  providers: [CHECKBOX_VALUE_OVERRIDE_ACCESSOR]
})

export class CheckboxControlValueOverrideAccessor implements ControlValueAccessor {
  onChange = (_: any) => {};
  onTouched = () => {};

  constructor(private _renderer: Renderer, private _elementRef: ElementRef) {}

  writeValue(value: any): void {
    this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value.checked);
  }
  registerOnChange(fn: (_: any) => {}): void { this.onChange = fn; }
  registerOnTouched(fn: () => {}): void { this.onTouched = fn; }

  setDisabledState(isDisabled: boolean): void {
    this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
  }
}