2016-10-13 40 views
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' 
} 

} 

回答

2
  • 代替NgFormControl类使用NgControl/@angular/forms
  • 代替[ngFormControl]指令,使用[formControl]

你还需要确保你@NgModule.imports: [ ReactiveFormsModule ]成任何模块使用形式的组件中声明。这是使用反应形式,即FormControl/FormGroup,但模板的形式,只要使用FormsModule。尽管你的例子看起来像是使用反应形式。但是您的指令也可以使用模板表单。

+1

具体而言,我使用了NgControl.control.setValue()和NgControl.valueAccessor.writeValue() – mishap