如何在Angular中转换ControlValueAccessor的值?

时间:2018-10-23 15:02:26

标签: angular

我有一个DatepickerComponent,但是在将其返回给其父级之前无法转换其值。 DatepickerComponent实现ControlValueAccessor以在反应形式中使用。

我需要DateTime类型用于在服务器端进行搜索。我想将form.value发送到服务器端进行搜索。

@Component({
  selector: 'datepicker',
  templateUrl: './datepicker.component.html',
  styleUrls: ['./datepicker.component.scss'],
  providers: [{
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => Datepicker2Component),
      multi: true,
    },
  ]
})
export class DatepickerComponent implements ControlValueAccessor {
  public _value: any;
  onChange: any = (newValue) => {
  };
  onTouched: any = () => {
  };

  get value() {
    //can I convert this._value here?
    //before return it to parent
    return this._value;
  }
  set value(val) {
    this._value = val;
    this.onChange(val);
  }

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

  registerOnTouched(fn) {
    this.onTouched = fn;
  }

  writeValue(val) {
    if (val && val !== this._value) {
      this._value = val;
    }
  }
}
<dp-date-picker
  dir="rtl"
  [(ngModel)]="value"
  mode="day"
  theme="dp-material">
</dp-date-picker>

0 个答案:

没有答案