gpt4 book ai didi

实现 ControlValueAccessor 的 Angular 2 指令不会在更改时更新 'touched' 属性

转载 作者:太空狗 更新时间:2023-10-29 17:07:15 25 4
gpt4 key购买 nike

我正在尝试为 Jquery UI Datepicker 创建自己的 Angular 2 指令。我在互联网上和 SO 中也看到了一些不同的方法,但没有人达到我想要的目标。所以这是我到目前为止的代码:

import {Directive, ElementRef, Input, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";

declare var $:any;

@Directive({
selector: '[date-picker]',
providers: [{
provide: NG_VALUE_ACCESSOR,useExisting:
forwardRef(() => DatePickerDirective),
multi: true
}]
})
export class DatePickerDirective implements ControlValueAccessor {
private value: string;

@Input('changeMonth') changeMonth:boolean = true;
@Input('changeYear') changeYear:boolean = true;

constructor(private el: ElementRef) {

}

ngAfterViewInit(){
$(this.el.nativeElement).datepicker({
changeMonth: this.changeMonth,
yearRange: "1:100",
changeYear: this.changeYear
}).on('change', e => this.onChange(e.target.value));
}

onChange: Function = () => {};

onTouched: Function = () => {};

writeValue(val: string) : void {
this.value = val;
}

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

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

发生的事情是,即使我选择一个日期(选择器)或直接在输入字段中键入它,它也不会更新“touched”属性。

您有任何修复它的想法吗?

最佳答案

对于那些最终遇到同样问题的人,我想出了一个解决方法,如下所示:

import {Directive, ElementRef, Input, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";

declare var $:any;

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

@Directive({
selector: '[date-picker]',
host: {'(blur)': 'onTouched($event)'},
providers: [CUSTOM_INPUT_DATE_PICKER_CONTROL_VALUE_ACCESSOR]
})
export class DatePickerDirective implements ControlValueAccessor {
private innerValue: string;

@Input('changeMonth') changeMonth:boolean = true;
@Input('changeYear') changeYear:boolean = true;

constructor(private el: ElementRef) {
$(this.el.nativeElement).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
}).on('change', e => this.onChange(e.target.value));
}

public onChange: any = (_) => { /*Empty*/ }
public onTouched: any = () => { /*Empty*/ }

get value(): any {
return this.innerValue;
};

//set accessor including call the onchange callback
set value(v: any) {
if (v !== this.innerValue) {
this.innerValue = v;
this.onChange(v);
}
}

writeValue(val: string) : void {
this.innerValue = val;
}

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

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

关于实现 ControlValueAccessor 的 Angular 2 指令不会在更改时更新 'touched' 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40694521/

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