gpt4 book ai didi

forms - FormControl 输入内的 Angular 2 日期管道

转载 作者:太空狗 更新时间:2023-10-29 17:05:14 24 4
gpt4 key购买 nike

我有一个动态生成的具有多个 FormControl 输入字段的 Angular 2 FormGroup。一些输入是日期,它们作为 unix 时间戳从服务器获取。

我想做的是:

  1. 能够将 unix 时间戳转换为人类可读的形式,当我的 FormGroup 被填充时,还有
  2. 翻译人类当表单为 unix 时间戳时日期的表示提交。

第 1 部分有点简单,像这样使用 Angular 的日期管道:

<input class="form-control" [formControlName]="question.key"
[value]="this.form.controls[this.question.key].value | date:'dd/MM/yyyy'">

其中this.form是对FormGroup的引用,this.question是基于官方动态表单教程的自定义包装类:

https://angular.io/docs/ts/latest/cookbook/dynamic-form.html

尝试以这种方式更改日期输入是行不通的,因为管道会不断尝试转换输入值,如果不抛出管道“DatePipe”异常的无效参数,则输入将无法使用。

澄清一下,我使用 FormGroup.patchValue() api 填写表单,并使用 FormGroup.getRawValue() api 提交表单数据。

我曾尝试使用 Angular 2 日期选择器组件,但它们使我的大型表单变得非常慢,所以我想在没有自定义日期选择器或任何依赖 jQuery 的小部件的情况下使用它。

提前致谢。

最佳答案

做这样的事情的一种方法是为您的输入创建一个实现 ControlValueAccessor 的组件。

A bridge between a control and a native element.

A ControlValueAccessor abstracts the operations of writing a new value to a DOM element representing an input control.

Please see DefaultValueAccessor for more information.

像这样的东西应该可以解决问题(未测试):

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

@Component({
template:`<input #input (input)="onChange($event)" (blur)="touchCallback()" type="date" [attr.disabled]="disabled?true:null">`
selector:"my-input",
styles:[],
providers:[DATE_VALUE_ACCESSOR]
})
export class MyDateInput implements ControlValueAccessor{
@ViewChild("input")
input:ElementRef;
disabled=false;
changeCallback=(data:any)=>{};
touchCallback=()=>{};

onChange(event){
let timestamp=this.convertToTimestamp(event.target.value);
this.changeCallback(timestamp);
}

convertToTimestamp(formatedDate){
//TODO:implement
}

convertFromTimestamp(timestamp){
//TODO:implement
}

writeValue(obj: any){
let formatedDate=this.convertFromTimestamp(obj);
this.input.nativeElement.value=formatedDate;
}

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

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

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

那么你应该可以像这样使用它:

<my-input class="form-control" [formControlName]="question.key"></my-input>

<my-input [(ngModel)]="myModel"></my-input>

关于forms - FormControl 输入内的 Angular 2 日期管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42254077/

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