Formatter and Parser-Equivalent in Angular 2

133 views
Skip to first unread message

Manfred Steyer

unread,
Jan 6, 2016, 4:58:12 PM1/6/16
to AngularJS

Hi,

I've searched the sources to find an equivalent to the Parser and Formatter-concept in AngularJS 1.x. As it looks like, we can use custom Value-Accessors to format and parse bindings.

  • Is this a good idea?
  • If yes, is the following implementation (that works and parses/formats a German Date in the format Day.Month.Year) ok?
  • We are using multi-bindings here. How does Angular 2 behave, when there is more then one Accessor for one component?

Wishes,
Manfred

import {Directive, Renderer, ElementRef, Self, forwardRef, Provider} from 'angular2/core';

import {NG_VALUE_ACCESSOR, DefaultValueAccessor } from 'angular2/common';
import {CONST_EXPR} from 'angular2/src/facade/lang';

const PROVIDER = CONST_EXPR(new Provider(
    NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => DateValueAccessor), multi: true}));

@Directive({
  selector:
      'input[date]',
  host: {'(input)': 'input($event.target.value)', '(blur)': 'blur()'},
  bindings: [PROVIDER]
})
export class DateValueAccessor extends DefaultValueAccessor {

    constructor(_renderer: Renderer, _elementRef: ElementRef) {
       super(_renderer, _elementRef);
    }

    blur() {
        this.onTouched();
    }

    input(value) {

        // Write back to model   
        if (value) {
            value = value.split(/\./);
            value = value[2] + "-" + value[1] + "-" + value[0];
        }

        this.onChange(value);
    }

    writeValue(value: any): void {

        // Write to view
        if (value) {
            var date = new Date(value);
            value = date.getDate() + "." + (date.getMonth()+1) + "." + date.getFullYear(); 
        }

        super.writeValue(value);

    }

} 

Günter Zöchbauer

unread,
Jan 7, 2016, 4:46:57 AM1/7/16
to AngularJS
Reply all
Reply to author
Forward
0 new messages