maj*_*odi 18 directive angular2-ngmodel angular
我想在使用属性Directive键入时更改(强制)输入字段值.有了它,我想创建一些指令,如大写,小写,maxlength,filterchar等,用于表单上的输入字段.我找到了这个例子:Angular 2 Attribute Directive Typescript Example但这似乎不起作用.也许它是为早期构建的Angular2做的.然而,这正是我想要做的.
当我创建这样的指令时:
import {Directive} from 'angular2/core';
import {NgModel} from 'angular2/common';
@Directive({
selector: '[ngModel][uppercase]',
host: {
'(input)' : 'onInputChange()'
}
})
export class UppercaseDirective{
constructor(public model:NgModel){}
onInputChange(){
var newValue = this.model.value.toUpperCase();
this.model.valueAccessor.writeValue(newValue);
this.model.viewToModelUpdate(newValue);
}
}
Run Code Online (Sandbox Code Playgroud)
并在这样的表单上使用它:
<input type="text" class="form-control" [(ngModel)]="field.name" ngControl="name" #name="ngForm" required uppercase>
Run Code Online (Sandbox Code Playgroud)
(并注册NgModel为提供者).我得到了
undefined this.model.value.
我可以使用$event.target.value = $event.target.value.toUpperCase()(当传递$event时onInputChange())并且适用于视图(它确实将输入显示为大写.但它不会更新绑定字段"field.name".
那么如何创建一个Angular2属性指令呢?
- 编辑 -
经过一番进一步调查后,我设法得到了我想要的东西.Günter提供的答案更接近我的初衷,也许更好.但这是另一种方式:
import {Directive, Input, Output, EventEmitter} from 'angular2/core';
@Directive({
selector: '[ngModel][uppercase]',
host: {
"(input)": 'onInputChange($event)'
}
})
export class UppercaseDirective{
@Output() ngModelChange:EventEmitter<any> = new EventEmitter()
value: any
onInputChange($event){
this.value = $event.target.value.toUpperCase()
this.ngModelChange.emit(this.value)
}
}
Run Code Online (Sandbox Code Playgroud)
正如我所说,我不确定这是否也是一个好方法,所以欢迎评论.
Rya*_*How 30
虽然Günter的答案看起来很有希望,但是有一个错误,即模型中的最终值以小写字母输入最后一个字母.
看这里:
https://plnkr.co/edit/SzxO2Ykg2pKq1qfgKVMH
请使用问题中提供的答案.它工作正常.
@Directive({
selector: '[ngModel][uppercase]',
host: {
"(input)": 'onInputChange($event)'
}
})
export class UppercaseDirective{
@Output() ngModelChange:EventEmitter<any> = new EventEmitter()
value: any
onInputChange($event){
this.value = $event.target.value.toUpperCase()
this.ngModelChange.emit(this.value)
}
}
Run Code Online (Sandbox Code Playgroud)
https://plnkr.co/edit/oE3KNMCG7bvEj8FV07RV
Gün*_*uer 12
更新
这种方法不能正常工作.请参阅@ RyanHow的答案以获得更好的解决方案.
原版的
@Directive({
selector: '[ngModel][uppercase]',
providers: [NgModel],
host: {
'(ngModelChange)' : 'onInputChange($event)'
}
})
export class UppercaseDirective{
constructor(private model:NgModel){}
onInputChange(event){
this.model.valueAccessor.writeValue(event.toUpperCase());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26625 次 |
| 最近记录: |