0
votes

I want to a create a RadioComponent which populates the input and Label.

I want this component to work with ngModel and reactive forms.

So i created a RadioGroup by implementing ControlValueAccessor, and RadioButton Component which populates Input and Label.

I am calling these component from a parent component where I defined FormGroup but reactive form is not working with this approach.

Can someone please suggest where I am going wrong.

https://stackblitz.com/edit/angular-mipzzw

RadioGroupComponent

import { Component, Input, forwardRef, ContentChildren, QueryList } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor, FormGroup } from '@angular/forms';
import { RadioButtonComponent } from '../radio-button/radio-button.component';

@Component({
  selector: 'radio-group',
  templateUrl: './radio-group.component.html',
  styleUrls: ['./radio-group.component.css'],
providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => RadioGroupComponent),
            multi: true
        }
    ],
})
export class RadioGroupComponent implements ControlValueAccessor {

  constructor() { }

 private _value: any = null;

    @ContentChildren(forwardRef(() => RadioButtonComponent), { descendants: true })
    radios: QueryList<RadioButtonComponent>;

    _onChange = (value: any) => {
        console.log('onChange=', value);
    }
    _onTouched = () => { };

    writeValue(value: any): void {
        console.log('writeValue=', value);
        this._onChange(value);
    }

    registerOnChange(fn: (_: any) => {}): void {
        this._onChange = fn;
    }

    registerOnTouched(fn: () => {}): void {
        this._onTouched = fn;
    }

    get value(): any {
        console.log('get value', this._value);
        return this._value;
    }

    set value(val) {  // this value is updated by programmatic changes
        if (val !== undefined && this._value !== val) {
            this._value = val;
            this._onChange(val);
            this._onTouched();
        }
    }
}

RadioComponent

import { Component, Input, Output, EventEmitter, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor, FormGroup } from '@angular/forms';

@Component({
    selector: 'radio-button',
    template: `
        <input type="radio"
            (change)="changeValue(value)"
            class="input-control"
            [id]="inputId"
            [(ngModel)]="selectedOption"
            [value]="value"
            [formControlName]="inputName"/>

        <label
            for="{{ inputId }}">
            <span>{{ label | translate }}</span>
        </label>
    `,        
    styleUrls: ['./radio.less']
})

export class RadioComponent {
    @Input() selectedOption: string;
    @Input() inputId: string;
    @Input() value: string;
    @Input() label: string;
    @Input() inputName: string;

    @Output() selectedOptionChange: EventEmitter<any> = new EventEmitter<any>();

    changeValue(value: any) {
        this.selectedOptionChange.emit(value);
    }                                            
}

Demo Component

import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-radio',
    template: `

            <div  [formGroup]="exampleForm">
                <radio-button *ngFor="let option of options"
                    [inputId] = "option.value"
                    [label]="option.display"
                    [value]="option.value"
                    (selectedOptionChange) = "selectedOptionChange($event)"
                    formInputName= "gender"
                    [selectedOption]="options[0].value">
                </radio-button>
            </div>

            </section>
            <h3>Selected value = {{selectedOption}} </h3>
            `,
})

export class DemoComponent implements OnInit {
    constructor(private fb: FormBuilder) { }

    exampleForm = this.fb.group({
        gender: ['', []],
    });

    selectedOption: string;

    options: Array<{ value: string, display: string }> = [
        { value: 'Male', display: 'Male' },
        { value: 'Female', display: 'Female' }
    ];

    ngOnInit() {
        this.selectedOptionChange(this.options[0].value);
    }

    selectedOptionChange(value: any): void {
        this.selectedOption = value;
    }
}
1

1 Answers

0
votes

You probably also need to ask for your formGroup as an Input

 @Input() group: FormGroup; 

and also you need an element that acts as container where you add the directive

[formGroup]

check the edit of your code I made

    import { Component, Input, Output, EventEmitter, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor, FormGroup } from '@angular/forms';


@Component({
  selector: 'radio-button',
  //You will also need a DOM element to act as a container of your formControl
  template: `
    <div [formGroup]="group">
        <input type="radio"
            (change)="changeValue(value)"
            class="input-control"
            [id]="inputId"
            [(ngModel)]="selectedOption"
            [value]="value"
            [formControlName]="inputName"/>

        <label
            for="{{ inputId }}">
            <span>{{ label | translate }}</span>
        </label>
        </div>
    `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => RadioComponent),
      multi: true
    }
  ],
  styleUrls: ['./radio.less']
})

export class RadioComponent implements ControlValueAccessor {
  @Input() selectedOption: string;
  @Input() inputId: string;
  @Input() value: string;
  @Input() label: string;
  @Input() inputName: string;
  @Input() group: FormGroup; //You also need to ask for the formgroup 

  @Output() selectedOptionChange: EventEmitter<any> = new EventEmitter<any>();

  changeValue(value: any) {
    this.selectedOptionChange.emit(value);
  }

  _onChange = (_: any) => { };
  _onTouched = () => { };


  writeValue(value: any): void {
    console.log('writeValue=', value);
    this._onChange(value);
  }


  registerOnChange(fn: (_: any) => {}): void {
    this._onChange = fn;
  }


  registerOnTouched(fn: () => {}): void {
    this._onTouched = fn;
  }
}

you could also post a working example so we could better help you. Maybe upload it to https://stackblitz.com


EDIT

For completeness sake I´ve also added the part of your demo component

import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-radio',
    template: `

            <div  [formGroup]="exampleForm">
                <radio-button *ngFor="let option of options"
                    [inputId] = "option.value"
                    [label]="option.display"
                    [value]="option.value"
                    (selectedOptionChange) = "selectedOptionChange($event)"
                    formInputName= "gender"
                    [selectedOption]="options[0].value"
                    [group]="exampleForm"
                    >
                </radio-button>
            </div>

            </section>
            <h3>Selected value = {{selectedOption}} </h3>
            `,
})

export class DemoComponent implements OnInit {
    constructor(private fb: FormBuilder) { }

    exampleForm = this.fb.group({
        gender: ['', []],
    });

    selectedOption: string;

    options: Array<{ value: string, display: string }> = [
        { value: 'Male', display: 'Male' },
        { value: 'Female', display: 'Female' }
    ];

    ngOnInit() {
        this.selectedOptionChange(this.options[0].value);
    }

    selectedOptionChange(value: any): void {
        this.selectedOption = value;
    }
}

EDIT: proof of concept

You can check a proof of concept here. It is a barebones version of what you are doing. It only has 3 components. The app-component, and two more similar to what you are doing.