如何进一步封装一个表单字段组件?

时间:2019-02-13 05:47:02

标签: angular

现在我在许多地方使用ngx-daterangepicker-material和以下重复代码,我想封装为独立的组件以供重用。

<div class="fx-date-range-container">
  <span class="summary">Summary</span>
  <input class="fx-date-range" type="text" matInput
         ngxDaterangepickerMd
         [locale]="{applyLabel: 'ok', format: 'MM-DD-YYYY'}"
         [drops]="'down'"
         [opens]="'right'"
         [ranges]="ranges"
         [showCustomRangeLabel]="false"
         [alwaysShowCalendars]="true"
         [keepCalendarOpeningWithRange]="true"
         [showCancel]="true"
         autocomplete="off"
         [(ngModel)]="selectedDateRange"
         (change)="getCampaignFXASummary()"
         name="daterange"/>
  <mat-icon class="icon-date-range" matSuffix>keyboard_arrow_down</mat-icon>
</div>

组件名称为fx-date-range-picker。 这是演示,我的问题是如何设置ngModel并将值传递给fx-date-range-picker组件。

也许我应该实现writeValue函数,但是不确定如何写。

https://ngx-daterangepicker-material-demo.stackblitz.io

1 个答案:

答案 0 :(得分:0)

您需要实现ControlValueAccessor

请参见angular.io文档 ControlValueAccessor

要实现的功能应类似于:

  export class [yourClass] implements ControlValueAccessor {      
  protected onChange: (value: any) => void = NOOP;
  protected internalValue: number;

  get value(): number {
    return this.internalValue;
  }

  set value(value: number) {
    if (value !== this.internalValue) {
      this.internalValue = value;
      this.onChange(value);
    }
  }

  writeValue(value) {
    this.value = value;
}
registerOnChange(fn) { this.onChange = fn;  }
registerOnTouched(fn) {  }

请参见下面的说明: https://blog.angularindepth.com/never-again-be-confused-when-implementing-controlvalueaccessor-in-angular-forms-93b9eee9ee83

祝你好运!