angular - 大写指令不更新输入角度
问题描述
这个大写指令不适用于 angular.... 如果我打印 console.log() 以查看格式方法的值,我可以看到我输入的值,但 inputText 上的文本不会更新为大写;
我对 html 的声明
<input type="text" uppercase >
import {Directive, Input, Output, EventEmitter, OnInit} from 'angular2/core';
@Directive({
selector: '[uppercase]',
host: {
'[value]': 'uppercase',
'(input)': 'format($event.target.value)'
}
})
export class Uppercase implements OnInit {
@Input() uppercase: string;
@Output() uppercaseChange: EventEmitter<string> = new EventEmitter<string>();
constructor() {
}
ngOnInit() {
this.uppercase = this.uppercase || '';
this.format(this.uppercase);
}
format(value) {
value = value.toUpperCase();
this.uppercaseChange.next(value);
}
}
我如何才能将文本大写?
解决方案
您可能需要像这样更新您的模板<input type="text" uppercase >
,以应用您的Directive
.
但纠正你的逻辑很重要,因为uppercase
指令将应用于nativeElement
类似的输入。
因此,您可能需要实现ControlValueAccessor接口并调整您的指令。
这是一个如何执行此操作的示例(我已经修改了您的代码):stackblitz 上的大写指令
我在代码中添加了一些注释。
让我知道这是否是您想要归档的内容。
编辑(看下面的评论)
如果您寻找一种更简单的方法来创建指令并保留您需要的两件事 输入文本应该是大写并且占位符应该是小写,您可以简单地执行以下操作
大写的.directive.ts
import { Directive,ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[uppercase]'
})
export class UppercaseDirective {
constructor(public ref: ElementRef) { }
@HostListener('input', ['$event']) onInput(event) {
this.ref.nativeElement.value = event.target.value.toUpperCase();
}
}
你的.template.html
<input placeholder="placeholder lowercase" uppercase type='text'>
我在这里做了另一个关于 stackblitz 的演示
推荐阅读
- google-cloud-platform - Google Cloud Storage 传输接收器前缀
- javascript - 如何在不使用内置 .repeat() 的情况下重复给定次数的字符串?
- java - 如何使用 API Gateway 代理在 AWS Lambda 中将多个文件作为多部分请求处理?
- excel - VBA 运行时错误 76 - 在 Excel 中找不到路径
- amazon-web-services - 使用 CloudFormation 模板在 Amazon S3 Glacier 中创建文件库
- javascript - 在 Gitlab Servicedesk 功能中将收集的电子邮件作为新票证/问题发送
- php - 评级值始终插入为 1
- python - Django中OAuth1.0a的验证POST请求
- python - 在 python 中使 Eratosthenes 的筛子更有效率?
- c# - ASP.NET Core 单元测试在测试控制器问题响应时抛出 Null Exception