angular - 如何修复 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>
解决方案
这是因为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
推荐阅读
- spring-cloud - 如何在不升级spring-cloud-dependencie版本的情况下升级spring-cloud-starter-openfeign版本
- flutter - 具有不同数据类型的 Dart 键值
- python - 在 Python 中查找与某个字符串相关的所有元组
- python - 当我有一组列表时,我想返回一个特定的列表
- matlab - 如何在时域中组合两个不同频率的信号
- ios - crashlytics 中应用程序的不同包标识符
- visual-studio - 为什么我在运行代码时看不到任何图形?
- google-apps-script - 如何格式化来自 Google Apps Script 的电子邮件正文中的日期?
- python - Python中的点系统
- node.js - Firebase Functions 记录对象占用大量空间