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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With