我有一个自定义的ControlValueAccessor,它只是在输入上附加货币符号。
@Component({
selector: 'app-currency-input',
templateUrl: './currency-input.component.html',
styleUrls: ['./currency-input.component.scss'],
providers: [
CurrencyPipe,
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CurrencyInputComponent),
multi: true
}
]
})
export class CurrencyInputComponent implements ControlValueAccessor {
@Input() class = '';
currencyValue: string;
onChange: (value: number) => void;
onTouched: () => void;
constructor(
private currencyPipe: CurrencyPipe
) { }
parseToNumber(currencyString: string) {
this.onChange(this.currencyPipe.parse(currencyString));
}
transformToCurrencyString(value: number): string {
return this.currencyPipe.transform(value);
}
writeValue(value: number): void {
if (value !== undefined) {
this.currencyValue = this.transformToCurrencyString(value);
}
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
}
CurrencyPipe
只是将字符串解析为数字并将数字转换为货币字符串(带有本地化的小数分隔符和货币符号)。
当我尝试使用这样的ReactiveForms时:
<app-currency-input
name="amount"
class="value-box"
formControlName="amount"
required
></app-currency-input>
...然后手动输入不会触发onChange()
。
我有一个解决方法,我订阅控件的valueChanges
,然后执行
control.patchValue(newValue, { emitModelToViewChange: true })
...成功触发ControlValueAccessor的onChange
。 (没有选项的patchValue
也会这样做,因为true
是此选项的默认值。我只是想指出罪魁祸首。)
但我希望使用内置的解决方案,该解决方案无法解决额外的必要检查和至少两个valueChanges。
一个简化的Plunker试用版:https://embed.plnkr.co/c4YMw87FiZMpN5Gr8w1f/
请参阅src/app.ts
中注释掉的代码。
答案 0 :(得分:2)
尝试这样的事情
import { Component, Input, forwardRef } from '@angular/core';
import { CurrencyPipe, } from '@angular/common';
import { ReactiveFormsModule, NG_VALUE_ACCESSOR, FormControl, ControlValueAccessor } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'currency-input',
template: `<input [formControl]="formControl" (blur)="onTouched()"/>`,
styles: [`h1 { font-family: Lato; }`],
providers: [
CurrencyPipe,
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CurrencyInputComponent),
multi: true
}
]
})
export class CurrencyInputComponent implements ControlValueAccessor {
constructor(private currencyPipe: CurrencyPipe) { }
private onChange: Function;
private onTouched: Function;
formControl = new FormControl('');
subscription: Subscription;
ngOnInit() {
this.subscription = this.formControl.valueChanges
.subscribe((v) => {
this.onChange && this.onChange(this.transform(v));
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
writeValue(val) {
this.formControl.setValue(this.transform(val), { emitEvent: false });
}
registerOnChange(fn) {
this.onChange = fn;
}
registerOnTouched(fn) {
this.onTouched = fn;
}
private transform(val: string) {
return this.currencyPipe.transform(val, 'USD')
}
}
请注意,我没有使用ReactiveFormsModule
,因此您需要将其导入模块中。