Skip to content

Instantly share code, notes, and snippets.

@JohnnyBravoNL
Created November 16, 2018 11:55
Show Gist options
  • Save JohnnyBravoNL/629c88515fb25c9705806b4f66884226 to your computer and use it in GitHub Desktop.
Save JohnnyBravoNL/629c88515fb25c9705806b4f66884226 to your computer and use it in GitHub Desktop.
Custom component - reactive forms
/*
Source: https://coryrylan.com/blog/angular-custom-form-controls-with-reactive-forms-and-ngmodel
*/
import { Component, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-switch',
templateUrl: 'app/switch.component.html',
styleUrls: ['app/switch.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SwitchComponent),
multi: true
}
]
})
export class SwitchComponent implements ControlValueAccessor {
@Input() label = 'switch';
@Input('value') _value = false;
onChange: any = () => { };
onTouched: any = () => { };
get value() {
return this._value;
}
set value(val) {
this._value = val;
this.onChange(val);
this.onTouched();
}
constructor() { }
registerOnChange(fn) {
this.onChange = fn;
}
registerOnTouched(fn) {
this.onTouched = fn;
}
writeValue(value) {
if (value) {
this.value = value;
}
}
switch() {
this.value = !this.value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment