3
入力をdd-mm-yyyyとしてフォーマットし、テキスト値とJavaScript日付を値として持つ属性ディレクティブが必要です。 rc.3で私はngFormControl.valueAccessor.writeValue()
と他のいくつかの方法を使用しました。今では、NgFormControlがリリース版でなくなっているようです。私は今何を使用すべきですか?ここで私は前にやっていたものです。入力ホストのテキストと値を変更する角度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