Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Value Accessor in Angular2

So I've got a formatting value accessor directive:

const CUSTOM_VALUE_ACCESSOR = new Provider(
    NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => NumbersValueAccessor), multi: true });

@Directive({
    selector: 'input[format]',
    host: { '(input)': 'onMyChange($event.target.value)' },
    providers: [CUSTOM_VALUE_ACCESSOR]
})  
export class NumbersValueAccessor extends DefaultValueAccessor {
//...
}

Then I use it like

@Component({
    templateUrl: 'frequencyPage.html'
    , moduleId: module.id
    , directives: [/*...*/ NumbersValueAccessor]
})
export class FrequencyPage //...

and in html as

  <input  format="{number:true}" [(ngModel)]="test.alpha"/>

It gets instantiated all right, but looking at the angular JIT compiled template code:

  self._DefaultValueAccessor_32_3 = new jit_DefaultValueAccessor3(self.renderer,new jit_ElementRef18(self._el_32));
  self._Token_NgValueAccessor_32_4 = [
    self._DefaultValueAccessor_32_3,
    self._DefaultValueAccessor_32_3
  ]
  ;
  self._NgModel_32_5 = new jit_NgModel5(null,null,null,self._Token_NgValueAccessor_32_4);
  self._NgControl_32_6 = self._NgModel_32_5;
  self._NgControlStatus_32_7 = new jit_NgControlStatus7(self._NgControl_32_6);
  self._NumbersValueAccessor_32_8 = new jit_NumbersValueAccessor8(self.renderer,new jit_ElementRef18(self._el_32));

it's created AFTER ngModel, therefore doesn't get passed to it, therefore when I'm actually editing the input it's the default value accessor that gets called. What am i missing?


EDIT: One thing I've found: if instead of extending DefaultValueAccessor I reimplement ControlValueAccessor from scratch, it works. Is it a bug in angular2's template compiler?

like image 848
TDaver Avatar asked Sep 25 '26 16:09

TDaver


1 Answers

Is it a bug in angular2's template compiler?

Yes It is, there are already multiple issues in github:

https://github.com/angular/angular/issues/9146#issuecomment-230410616

It seems like the decorators are not able to override the metadata of the angular2-classes.


More issues that are related to this metadata bug:

https://github.com/angular/angular/issues/9758

https://github.com/angular/angular/issues/8925

like image 191
Dinistro Avatar answered Sep 27 '26 06:09

Dinistro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!