Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created May 22, 2018 21:36
Show Gist options
  • Save amcdnl/086ec1309996ce528b285e65dfb77de0 to your computer and use it in GitHub Desktop.
Save amcdnl/086ec1309996ce528b285e65dfb77de0 to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import { NgControl } from '@angular/forms';
/**
* Inspired by https://goo.gl/Xrhoku
*/
@Injectable()
export class RadioControlRegistry {
private _accessors: any[] = [];
add(control: NgControl, accessor: any) {
this._accessors.push([control, accessor]);
}
remove(accessor: any) {
for (let i = this._accessors.length - 1; i >= 0; --i) {
if (this._accessors[i][1] === accessor) {
this._accessors.splice(i, 1);
return;
}
}
}
select(accessor: any) {
this._accessors.forEach(c => {
if (this._isSameGroup(c, accessor)) {
c[1].writeValue(accessor.value);
}
});
}
private _isSameGroup(controlPair: [any, any], accessor: any): boolean {
if (!controlPair[0].control) {
return false;
}
return controlPair[0]._parent === accessor._control._parent && controlPair[1].name === accessor.name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment