Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get FormControl instance from ControlValueAccessor

Tags:

I've the following component:

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

I can assign and alter the value through these inputs:

<pc-radio-button [formControl]="formControl"></pc-radio-button> <pc-radio-button [formControlName]="inputControlName"></pc-radio-button> 

However I need the component to have the direct access to the assigned formControl, as I need to add styles depending on its status.

By creating an @Input() formControl does not solve the problem. As it does not cover the case when form control is assigned via formControlName.

like image 536
Gediminas Bublys Avatar asked Aug 18 '17 11:08

Gediminas Bublys


2 Answers

It looks like injector.get(NgControl) is throwing a deprecation warning, so I wanted to chime in with another solution:

constructor(public ngControl: NgControl) {   ngControl.valueAccessor = this; } 

The trick is to also remove NG_VALUE_ACCESSOR from the providers array otherwise you get a circular dependency.

More information about this is in this talk by Kara Erickson of the Angular team.

like image 84
Jesse Avatar answered Sep 20 '22 17:09

Jesse


One possible solution is to get NgControl instance via Injector:

import { NgControl } from '@angular/forms'; export class PasswordComponent implements ControlValueAccessor {   ...   ngControl: NgControl;    constructor(private inj: Injector) {     ...   }    ngOnInit() {     this.ngControl = this.inj.get(NgControl)   } 

then you can get status like

ngControl.control.status 

See also

  • Access valid value of custom form control
like image 38
yurzui Avatar answered Sep 23 '22 17:09

yurzui