值未从带有 ControlValueAccessor 的自定义控件传播 [英] Value not propagated from custom control with ControlValueAccessor

查看:22
本文介绍了值未从带有 ControlValueAccessor 的自定义控件传播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个自定义控件,其中包含一个选择组件.但在我的反应形式中,价值永远不会传播.

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

有人可以帮我吗?

我的自定义控件:

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;
}

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

推荐答案

因为当值改变时你没有调用onChangeCallback:

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.

您缺少的第二件事是将选择框从模型更新为模板,在我的 plunker 中,我还添加了解决方案.

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.

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

这篇关于值未从带有 ControlValueAccessor 的自定义控件传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆