【发布时间】:2016-10-09 05:24:00
【问题描述】:
我试图在输入字段格式/掩码值时输入它们,同时让实际模型保留原始(或不同格式的)值。我在考虑电话号码等,但为简单起见,我使用大写字母进行测试。
我尝试了很多东西,希望它像指令一样简单。但似乎无法让显示值偏离表单值。
plunk: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>
【问题讨论】:
-
为什么不用管道?听起来您只是想要一种不同的文本显示方式。
-
我希望在输入框中进行格式化 - 输入掩码。我只是出于测试目的在视图中显示值。
标签: angular angular2-directives angular2-forms