首页 > 解决方案 > 如何修复 ControlValueAccessor 中的“获取价值”

问题描述

我有一个自定义组件(ControlValueAccessor)。在这个组件内部,当(focusout)我尝试获取“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>

标签: angular

解决方案


这是因为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


推荐阅读