From a9f2120dbe8ed72ef6cca029e930f4ef08cc3d2d Mon Sep 17 00:00:00 2001
From: anandtiwary <52081890+anandtiwary@users.noreply.github.com>
Date: Thu, 9 Dec 2021 09:55:38 -0800
Subject: [PATCH] refactor: making radio forms compatible with forms
---
.../src/radio/radio-group.component.ts | 35 +++++++++++++++++--
1 file changed, 32 insertions(+), 3 deletions(-)
diff --git a/projects/components/src/radio/radio-group.component.ts b/projects/components/src/radio/radio-group.component.ts
index ee8c07f0c..634955278 100644
--- a/projects/components/src/radio/radio-group.component.ts
+++ b/projects/components/src/radio/radio-group.component.ts
@@ -1,4 +1,5 @@
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output, TemplateRef } from '@angular/core';
+import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { MatRadioChange } from '@angular/material/radio';
import { LoggerService } from '@hypertrace/common';
import { RadioOption } from './radio-option';
@@ -6,6 +7,13 @@ import { RadioOption } from './radio-option';
@Component({
selector: 'ht-radio-group',
styleUrls: ['./radio-group.component.scss'],
+ providers: [
+ {
+ provide: NG_VALUE_ACCESSOR,
+ useExisting: RadioGroupComponent,
+ multi: true
+ }
+ ],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@@ -34,7 +42,7 @@ import { RadioOption } from './radio-option';
`
})
-export class RadioGroupComponent implements OnInit {
+export class RadioGroupComponent implements ControlValueAccessor, OnInit {
@Input()
public title!: string;
@@ -53,6 +61,9 @@ export class RadioGroupComponent implements OnInit {
@Output()
public readonly selectedChange: EventEmitter = new EventEmitter();
+ private propagateControlValueChange?: (value: string | undefined) => void;
+ private propagateControlValueChangeOnTouch?: (value: string | undefined) => void;
+
public constructor(private readonly loggerService: LoggerService) {}
public ngOnInit(): void {
@@ -69,14 +80,32 @@ export class RadioGroupComponent implements OnInit {
}
}
+ public writeValue(value?: string): void {
+ this.setSelection(value);
+ }
+
+ public registerOnChange(onChange: (value?: string) => void): void {
+ this.propagateControlValueChange = onChange;
+ }
+
+ public registerOnTouched(onTouch: (value?: string) => void): void {
+ this.propagateControlValueChangeOnTouch = onTouch;
+ }
+
public onRadioChange(event: MatRadioChange): void {
- this.selected = this.options.find(option => option.value === event.value);
- this.selectedChange.emit(event.value);
+ this.setSelection(event.value);
}
public isLabelAString(label: string | TemplateRef): boolean {
return typeof label === 'string';
}
+
+ private setSelection(value: string | undefined): void {
+ this.selected = this.options.find(option => option.value === value);
+ this.selectedChange.emit(value);
+ this.propagateControlValueChange?.(value);
+ this.propagateControlValueChangeOnTouch?.(value);
+ }
}
export const enum OptionsDirection {