cebor
cebor

Reputation: 6546

Custom Control: ControlValueAccessor does not work

I have a component which is wrapping a form control input field, for this i'm trying to implement the ControlValueAccessor.

But i don't get it working.

custom-input.component.ts:

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

const noop = () => {};

@Component({
  selector: 'custom-input',
  template: '<input [(ngModel)]="value" (blur)="onBlur()">{{value}}'
})
export class CustomInputComponent implements ControlValueAccessor {
  private onTouchedCallback: () => void = noop;
  private onChangeCallback: (_: any) => void = noop;

  private _value: any = '';

  get value() {
    return this._value;
  }
  set value(v: any) {
    if (v !== this._value) {
      this._value = v;
      this.onChangeCallback(v);
    }
  }

  onBlur() {
    this.onTouchedCallback();
  }

  writeValue(value: any): void {
    this._value = value;
  }
  registerOnChange(fn: any): void {
    this.onChangeCallback = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouchedCallback = fn;
  }
}

And i use it like this:

<custom-input [(ngModel)]="foo"></custom-input>

Exception:

No value accessor for form control with unspecified name attribute

Angular Verion: 2.1.2

Plunker: http://plnkr.co/edit/PgL81hTMdwJpPUs4wOOU?p=preview

Upvotes: 0

Views: 4980

Answers (1)

yurzui
yurzui

Reputation: 214295

You have to provide custom NG_VALUE_ACCESSOR like:

export const TEST_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => TestComponent),
    multi: true
};
@Component({
  selector: 'test',
  template: '<input [(ngModel)]="value" (blur)="onBlur()">{{value}}',
  providers: [TEST_VALUE_ACCESSOR]  // <== this line
})
export class TestComponent implements ControlValueAccessor {

http://plnkr.co/edit/VEWs1n8kbWs7riacSVu3?p=preview

Upvotes: 2

Related Questions