gpt4 book ai didi

angular - 如何修复 ControlValueAccessor 中的 'get value'

转载 作者:行者123 更新时间:2023-12-04 17:38:02 25 4
gpt4 key购买 nike

我有一个自定义组件 (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);
}

}

日期.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 有一个单向属性绑定(bind),即 [value]="value", View 中的更改不会更改变量的内容 。如果要获取当前值使用,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

关于angular - 如何修复 ControlValueAccessor 中的 'get value',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55844104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com