3
我需要一个属性指令,将输入格式化为dd-mm-yyyy并将其作为文本值并根据javascript日期作为值。在rc.3我使用ngFormControl.valueAccessor.writeValue()
和其他一些方法。现在似乎NgFormControl在发布版本中没有了。我现在应该使用什么?以下是我在做之前:Angular 2属性指令修改输入主机文本和值
<input type="text" format-date2 [ngFormControl]='formControls.dateOfMarriage'>
import {Directive, ElementRef} from '@angular/core';
import {NgFormControl} from '@angular/common';
@Directive({
selector: '[format-date2]',
host: {
'(input)': 'onInputChange()',
'placeholder': 'dd-mm-yyyy',
},
})
export class FormatDate2 {
viewValue;
modelValue;
currentValue = '';
el: HTMLInputElement;
constructor(private model: NgFormControl, private elementRef: ElementRef) {
this.el = elementRef.nativeElement;
}
ngOnInit() {
if (this.model.control.value) {
let d = new Date(this.model.control.value);
let s = this.pad(d.getDate()) + '-' + this.pad(d.getMonth() + 1) + '-' + d.getFullYear();
this.model.valueAccessor.writeValue(s);
}
}
pad(n) {
return n < 10 ? '0' + n : n;
}
onInputChange() {
let i = this.el.selectionEnd - this.el.value.length;
this.format(this.el.value);
i = this.viewValue.length + i;
this.model.control.updateValue(this.modelValue);
this.model.valueAccessor.writeValue(this.viewValue);
this.el.setSelectionRange(i, i);
return false;
}
format(val) {
// some code
// this.modelValue = 'some value';
// this.viewValue = 'another value'
}
}
具体而言,我使用了NgControl.control.setValue()和NgControl.valueAccessor.writeValue() – mishap