Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value not propagated from custom control with ControlValueAccessor

Tags:

angular

i have the this Custom Control which includes a select component. But in my reactive form the value is never propagated.

Can somebody help me with that?

My custom control:

const SOME_SELECT_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => SomeSelectComponent),
  multi: true
};

@Component({
  selector: 'some-select',
  template: `
  <select class="form-control">
  <option value="" disabled>Bitte wählen sie einen Eintrag aus aus</option>
  <option *ngFor="let item of optionItems" value="{{ item.id }}">
    {{ item.name }}
  </option>
</select>
  `,
  providers: [SOME_SELECT_VALUE_ACCESSOR]
})
export class SomeSelectComponent implements OnInit, ControlValueAccessor {

  private _value: any;

  @Input() optionItems: Array<OptionItem> = [];

  private onTouchedCallback: () => void;
  private onChangeCallback: (_: any) => void;

  ngOnInit(): void {
  }

  writeValue(obj: any): void {
    console.log(obj);
    if (this._value !== obj) {
      this._value = obj;
    }
  }

  registerOnChange(fn: any): void {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouchedCallback = fn;
  }

}

export interface OptionItem {
  key: String;
  value: String;
}

A plnkr: https://plnkr.co/edit/VNflDbpMm1VmfIHcMcXr?p=preview

like image 605
stranger-thing Avatar asked Dec 19 '16 15:12

stranger-thing


Video Answer


1 Answers

Because you don't call the onChangeCallback when the value is changed:

<select class="form-control" (change)="change(select.value)" #select>

change(val) {
  this.onChangeCallback(val);
}

Now you can see the control value changed.

The second thing that you are missing is update the select box from the model to template, in my plunker I also added the solution.

Working plunker: https://plnkr.co/edit/C5mwsDre8OCkWYCDOF4i?p=preview

like image 95
Bazinga Avatar answered Oct 21 '22 15:10

Bazinga