角度 – 使用ngModel更改字段值的属性指令
发布时间:2020-12-17 07:48:25 所属栏目:安全 来源:网络整理
导读:我想在使用属性指令输入时更改(强制)输入字段值.有了它,我想创建大写字母,小写,maxlength,filterchar等的指令,以便在窗体的输入字段上使用.我发现这个例子: Angular 2 Attribute Directive Typescript Example,但这似乎不起作用.也许这是为了早期建立的A??n
我想在使用属性指令输入时更改(强制)输入字段值.有了它,我想创建大写字母,小写,maxlength,filterchar等的指令,以便在窗体的输入字段上使用.我发现这个例子:
Angular 2 Attribute Directive Typescript Example,但这似乎不起作用.也许这是为了早期建立的A??ngular2.然而,我正在做什么.
当我创建一个这样的指令时: 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); } } 并在这样的表单上使用它: <input type="text" class="form-control" [(ngModel)]="field.name" ngControl="name" #name="ngForm" required uppercase> (并将NgModel注册为提供商).我得到了
我可以使用$event.target.value = $event.target.value.toUpperCase()(当使用onInputChange()传递$event时),并且可以用于视图(它将输入显示为大写,t更新绑定字段“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) } } 正如我所说,我不知道这是否也是一个很好的方法,所以评论是受欢迎的.
更新
这种方法不能正常工作.请参阅@ 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()); } } Plunker (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容