3

I need to have an attribute directive that will format the input as dd-mm-yyyy and have it as text value and according javascript date as value. At rc.3 I used ngFormControl.valueAccessor.writeValue() and a few other methods. Now in it seems that NgFormControl is gone in the release version. What should i be using now? Here is what I was doing before:

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

}

1 Answer 1

2
  • Instead of NgFormControl class use NgControl / @angular/forms
  • Instead of [ngFormControl] directive, use [formControl].

You also need to make sure that you @NgModule.imports: [ ReactiveFormsModule ] into whatever module the component using the forms is declared in. This is for using reactive forms, i.e FormControl/FormGroup, but template forms, just use FormsModule. Your example though looks like it's using reactive forms. But your directive will work with template forms also.

Sign up to request clarification or add additional context in comments.

1 Comment

Specifically I used NgControl.control.setValue() and NgControl.valueAccessor.writeValue()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.