我正在尝试通过实现ControlValueAccessor来创建自定义复选框。自定义复选框接受这两个字符串值'Y'或'N'。为了使它在复选框上工作,我创建了一个内部ngModel,其中包含自定义组件,它将值('Y'或'N')设置为布尔值,并将其从布尔值返回到字符串。
这是代码。我
import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
const noop = () => {
};
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomCheckboxComponent),
multi: true
};
@Component({
selector: 'custom-checkbox',
templateUrl: '<input type="checkbox" [(ngModel)]="internalCheckbox">',
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CustomCheckboxComponent implements ControlValueAccessor {
internalChecbox: boolean = false;
//Placeholders for the callbacks which are later providesd
//by the Control Value Accessor
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;
//get accessor
get value(): any {
return this.internalChecbox == true ? 'Y' : 'N';
};
//set accessor including call the onchange callback
set value(value: any) {
this.internalChecbox = value=='Y' ? true: false;
}
//Set touched on blur
onBlur() {
this.onTouchedCallback();
}
//From ControlValueAccessor interface
writeValue(value: any) {
if (value !== this.internalChecbox) {
this.internalChecbox = value;
}
}
//From ControlValueAccessor interface
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
//From ControlValueAccessor interface
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
}
我不知道为什么它不起作用而且我总是得到零值。
答案 0 :(得分:0)
永远不会调用onChangeCallback函数。这是angular知道自定义组件中的值已更改并且需要在表单中更新的唯一方法。因此,只要组件中的值更新,就需要执行该函数:
this.onChangeCallback(this.internalCheckbox);