2016-06-08 77 views
5

我尝试在输入字段格式/掩码值时键入,而实际模型保留原始(或不同格式)值。我正在考虑电话号码等,但为了简单起见,我使用大写字母进行测试。Angular 2 - 输入掩码:输入框显示格式化值,而模型保留未格式化的值

我试过一堆东西,希望它像指令一样简单。但似乎无法使显示值偏离表单值。

普拉克:http://plnkr.co/edit/VH5zn4S8q28CBpFutBlx?p=preview

这里的指令:

@Directive({ 
    selector: '[uppercase]', 
    host: { 
    '(input)': 'onInputChange()', 
    } 
}) 

export class UppercaseDirective { 

    constructor(private model: NgFormControl) { } 

    onInputChange() { 
    let newValue = this.model.value.toUpperCase(); 
    this.model.viewToModelUpdate(newValue); 
    this.model.valueAccessor.writeValue(newValue); 
    } 

} 

和形式:

<form [ngFormModel]='myForm'> 
    <input [ngFormControl]='myForm.controls.field' uppercase> 
    <div> 
    {{ myForm.value.field }} 
    </div> 
</form> 
+0

为什么不能管?听起来像你只是想要一种不同的方式来显示文字。 –

+0

我想要在输入框中输入格式 - 输入掩码。我只在测试中显示视图中的值。 – Steve

回答

3

尝试直接更新控制参考这样的:

onInputChange() { 
    let newValue = this.model.value.toUpperCase(); 
    this.model.control.updateValue(newValue); 
} 

参见plunker http://plnkr.co/edit/XYPWYgA8lbg2EdxPqzWj?p=preview

+0

有道理。谢谢。我试图让模型的价值和展示价值不同,但你的答案给了我答案:http://plnkr.co/edit/VH5zn4S8q28CBpFutBlx?p=preview – Steve

1

说实话,我仍然在学习angular2和高科技仍然是真正的不成熟说这是做到这一点的最好方式,但在玩过之后:

import {Directive, ElementRef, Output, EventEmitter} from '@angular/core'; 
import {NgFormControl} from '@angular/common'; 

@Directive({ 
    selector: '[uppercase]', 
    host: { 
    '(input)': 'onInputChange()', 
    } 
}) 

export class UppercaseDirective { 

    @Output() onChange = new EventEmitter(); 
    rawValue: string = ''; 

    constructor(private model: NgFormControl, private elementRef: ElementRef) { } 

    onInputChange() { 
    let str = this.model.value; 
    this.rawValue = this.rawValue.substring(0, str.length) + str.substring(this.rawValue.length, str.length); 
    let newValue = this.rawValue.toUpperCase(); 
    this.model.viewToModelUpdate(newValue); 
    this.model.valueAccessor.writeValue(newValue); 
    this.onChange.emit(this.rawValue); 
    } 

} 

那么你可以这样说:

<input [ngFormControl]='myForm.controls.field' uppercase (onChange)="raw = $event"> 
<div> 
    {{ raw }} 
</div> 

因为每当你更新模型,变量会发生变化。你必须做的是分开的。尝试在你的plnkr,它的工作。

编辑: 可能需要为不同的场景有些工作虽然哈哈

+0

谢谢埃德。我试图实现的是,表单模型包含原始值。 – Steve

+0

@Steve这可能会让你感兴趣http://stackoverflow.com/questions/37800841/input-mask-fields-in-angular2-forms –