Angular 2 属性指令修改输入主机文本和值

Angular 2 attribute directive to modify the input host text and value

我需要一个属性指令,将输入格式化为 dd-mm-yyyy 并将其作为文本值,并根据 javascript 日期作为值。在 rc.3 中,我使用了 ngFormControl.valueAccessor.writeValue() 和其他一些方法。现在看来 NgFormControl 在发布版本中已经消失了。我现在应该用什么?这是我之前所做的:

<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' 
}

}
  • 而不是 NgFormControl class 使用 NgControl / @angular/forms
  • 而不是 [ngFormControl] 指令,使用 [formControl].

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