如何在ControlValueAccessor中修复“获取价值”

时间:2019-04-25 07:36:01

标签: angular

我有一个自定义组件(ControlValueAccessor)。在此组件内部,当(聚焦)时,我尝试获取“ this.value”,但它给了我旧的值,这是什么问题?

这是我的date.component.ts

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => DateComponent),
  multi: true
};

@Component({
  selector: 'app-date',
  templateUrl: './date.component.html',
  styleUrls: ['./date.component.css'],
  providers: [
    CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR
  ],
})
export class DateComponent implements ControlValueAccessor {

  value: any;
  onChange: any = () => { };
  onTouched: any = () => { };
  disabled: boolean;

  NormalizedDate(): void {
    console.log(this.value); // here I want to get the value,and expect to get value from "formControlName", but it doesn't work
  }

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

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

  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  writeValue(obj: any): void {
    this.value = obj ? obj : '';
    this.onChange(obj);
  }

}

date.component.html

<mat-form-field class="full-width" appearance="outline">
  <mat-label>{{label}}</mat-label>
  <input matInput [matDatepicker]="picker" [value]="value" [disabled]="disabled"
         (dateChange)="onChange($event.target.value)"
         (blur)="onTouched()"
         (focusout)="NormalizedDate()"
  >
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

app.component.ts(这是我的自定义组件的呈现位置。)

<div class="col-md-4">
          <app-date formControlName="createDate"></app-date>
        <h1>{{form.controls.createDate.value}}</h1>
      </div>

1 个答案:

答案 0 :(得分:0)

这是因为value具有单向属性绑定,即[value]="value",视图中的更改不会更改变量value的内容。如果要获取当前值,请使用normalizedDate($event.target.value)

<input matInput [matDatepicker]="picker" [value]="value" [disabled]="disabled"
     (dateChange)="onChange($event.target.value)"
     (blur)="onTouched()"
     (focusout)="normalizedDate($event.target.value)">


  normalizedDate(val): void {
     console.log(val);
  }

在此处查看示例:https://stackblitz.com/edit/controlvalueaccessorgeneric-4rabaq?file=src/app/app.component.ts