Ich muss eine Attribut-Direktive haben, die die Eingabe als TT-MM-JJJJ formatiert und als Textwert und entsprechendem JavaScript-Datum als Wert hat. Bei rc.3 habe ich ngFormControl.valueAccessor.writeValue()
und ein paar andere Methoden verwendet. Jetzt scheint es, dass NgFormControl in der Release-Version verschwunden ist. Was soll ich jetzt benutzen? Hier ist, was ich tat vor:Angular 2 Attribut-Direktive zum Ändern des Eingabe-Host-Textes und Wert
<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'
}
}
Insbesondere habe ich NgControl.control.setValue() und NgControl.valueAccessor.writeValue() verwendet – mishap