11import { ChangeDetectionStrategy , Component , EventEmitter , Input , OnInit , Output , TemplateRef } from '@angular/core' ;
2+ import { ControlValueAccessor , NG_VALUE_ACCESSOR } from '@angular/forms' ;
23import { MatRadioChange } from '@angular/material/radio' ;
34import { LoggerService } from '@hypertrace/common' ;
45import { RadioOption } from './radio-option' ;
56
67@Component ( {
78 selector : 'ht-radio-group' ,
89 styleUrls : [ './radio-group.component.scss' ] ,
10+ providers : [
11+ {
12+ provide : NG_VALUE_ACCESSOR ,
13+ useExisting : RadioGroupComponent ,
14+ multi : true
15+ }
16+ ] ,
917 changeDetection : ChangeDetectionStrategy . OnPush ,
1018 template : `
1119 <ht-label *ngIf="this.title" class="title" [label]="this.title"></ht-label>
@@ -34,7 +42,7 @@ import { RadioOption } from './radio-option';
3442 <ng-template #defaultLabel let-label><ht-label class="radio-button-label" [label]="label"></ht-label></ng-template>
3543 `
3644} )
37- export class RadioGroupComponent implements OnInit {
45+ export class RadioGroupComponent implements ControlValueAccessor , OnInit {
3846 @Input ( )
3947 public title ! : string ;
4048
@@ -53,6 +61,9 @@ export class RadioGroupComponent implements OnInit {
5361 @Output ( )
5462 public readonly selectedChange : EventEmitter < string > = new EventEmitter ( ) ;
5563
64+ private propagateControlValueChange ?: ( value : string | undefined ) => void ;
65+ private propagateControlValueChangeOnTouch ?: ( value : string | undefined ) => void ;
66+
5667 public constructor ( private readonly loggerService : LoggerService ) { }
5768
5869 public ngOnInit ( ) : void {
@@ -69,14 +80,32 @@ export class RadioGroupComponent implements OnInit {
6980 }
7081 }
7182
83+ public writeValue ( value ?: string ) : void {
84+ this . setSelection ( value ) ;
85+ }
86+
87+ public registerOnChange ( onChange : ( value ?: string ) => void ) : void {
88+ this . propagateControlValueChange = onChange ;
89+ }
90+
91+ public registerOnTouched ( onTouch : ( value ?: string ) => void ) : void {
92+ this . propagateControlValueChangeOnTouch = onTouch ;
93+ }
94+
7295 public onRadioChange ( event : MatRadioChange ) : void {
73- this . selected = this . options . find ( option => option . value === event . value ) ;
74- this . selectedChange . emit ( event . value ) ;
96+ this . setSelection ( event . value ) ;
7597 }
7698
7799 public isLabelAString ( label : string | TemplateRef < unknown > ) : boolean {
78100 return typeof label === 'string' ;
79101 }
102+
103+ private setSelection ( value : string | undefined ) : void {
104+ this . selected = this . options . find ( option => option . value === value ) ;
105+ this . selectedChange . emit ( value ) ;
106+ this . propagateControlValueChange ?.( value ) ;
107+ this . propagateControlValueChangeOnTouch ?.( value ) ;
108+ }
80109}
81110
82111export const enum OptionsDirection {
0 commit comments