Created
January 28, 2019 11:02
-
-
Save zalito12/d50d72b8310067118257c91b25c0bd82 to your computer and use it in GitHub Desktop.
Custom input component with ngModel support (Angular 6)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(() => ThemeCheckComponent), | |
multi: true | |
}; | |
@Component({ | |
selector: 'app-custom-input', | |
templateUrl: './custom-input.component.html', | |
styleUrls: ['./custom-input.component.css'], | |
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR] | |
}) | |
export class ThemeCheckComponent implements ControlValueAccessor { | |
// The internal data model | |
private innerValue = false; | |
// Placeholders for the callbacks which are later provided | |
// by the Control Value Accessor | |
private onTouchedCallback: () => void = noop; | |
private onChangeCallback: (_: any) => void = noop; | |
// get accessor | |
get value(): boolean { | |
return this.innerValue; | |
} | |
// set accessor including call the onchange callback | |
set value(v: boolean) { | |
this.setValue(v); | |
} | |
private setValue(v: boolean) { | |
if (v !== this.innerValue) { | |
this.innerValue = v; | |
this.onChangeCallback(v); | |
} | |
} | |
// From ControlValueAccessor interface | |
writeValue(value: boolean) { | |
if (value !== this.innerValue) { | |
this.innerValue = value; | |
} | |
} | |
// From ControlValueAccessor interface | |
registerOnChange(fn: any) { | |
this.onChangeCallback = fn; | |
} | |
// From ControlValueAccessor interface | |
registerOnTouched(fn: any) { | |
this.onTouchedCallback = fn; | |
} | |
constructor() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment