更新:最初雖然問題在於ControlValueAccessor的實現,隨後確定的問題是將ControlValueAccessor應用於子元素。編輯反映的問題。如何實現離子輸入的貨幣輸入指令
我想提供一個屬性指令,它將以'美元'格式(例如10.00)顯示貨幣值,但會以美分(例如1000)的形式存儲在底層模型中。
<!-- cost = 1000 would result in text input value of 10.00
<input type="text" [(ngModel)]="cost" name="cost" currencyInput>
<!-- or in Ionic 2 -->
<ion-input type="text" [(ngModel)]="cost" name="cost-ionic" currencyInput>
以前在AngularJS 1.x中我會使用解析和渲染在指令鏈路功能如下:
(function() {
'use strict';
angular.module('app.directives').directive('ndDollarsToCents', ['$parse', function($parse) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
var listener = function() {
element.val((value/100).toFixed(2));
};
ctrl.$parsers.push(function(viewValue) {
return Math.round(parseFloat(viewValue) * 100);
});
ctrl.$render = function() {
element.val((ctrl.$viewValue/100).toFixed(2));
};
element.bind('change', listener);
}
};
}]);
})();
在離子2 /角2 I實現此使用ControlValueAccessor接口具有如下:
import { Directive, Renderer, ElementRef, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
const CURRENCY_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CurrencyInputDirective),
multi: true
}
@Directive({
selector: '[currencyInput]',
host: {
'(input)': 'handleInput($event.target.value)'
},
providers: [ CURRENCY_VALUE_ACCESSOR ]
})
export class CurrencyInputDirective implements ControlValueAccessor, AfterViewInit
{
onChange = (_: any) => {};
onTouched =() => {};
inputElement: HTMLInputElement = null;
constructor(private renderer: Renderer, private elementRef: ElementRef) {}
ngAfterViewInit()
{
let element = this.elementRef.nativeElement;
if(element.tagName === 'INPUT')
{
this.inputElement = element;
}
else
{
this.inputElement = element.getElementsByTagName('input')[0];
}
}
registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
registerOnTouched(fn:() => void): void { this.onTouched = fn; }
handleInput(value : string)
{
if (value)
{
value = String(Math.round(parseFloat(value) * 100));
}
this.onChange(value);
}
writeValue(value: any): void
{
if (value)
{
value = (parseInt(value)/100).toFixed(2);
}
this.renderer.setElementProperty(this.inputElement, 'value', value);
}
}
雖然這適用於直接輸入元素時適用於離子輸入它不起作用罰款。有沒有辦法讓ControlValueAccessor應用於離子輸入的子輸入元素?
輸入和輸出??示例 – Aravind
在下面看到我的答案 – Aravind