我需要让整个应用程序在打字时有大写字母,所以我试着在HTML中使用如下。
#input (input)="input.value=$event.target.value.toUpperCase()"
而且我还通过一个指令,使得输入在打字时变成大写字母,但这两个东西都不允许。ctrl + z
,当我做 ctrl + z
如果输入字段是空的,它必须给我空的值,当编辑模式下,如果已经有值,我们尝试编辑,并进行 ctrl + z
然后我们需要获取已经存储的值。
DEMO.DEMO LInkDEMO LInk
我尝试的DEMO。DEMO 我试过的东西的链接谁能帮我解决这个问题
你需要在angular上绑定keyup事件。下面是一个例子。
<input type="text" onkeyup="this.value = this.value.toUpperCase();">
你可以使用自定义指令,就像下面的代码一样,你可以使用toUpperCase()来修剪每个输入元素的字符串。
import { Directive, ElementRef, HostListener, Output, EventEmitter } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: 'input[type="text"], input[type="email"], input[type="number"], textarea, input[type="password"]',
providers: [NgModel]
})
export class StringTrimDirective {
@Output() ngModelChange: EventEmitter<any> = new EventEmitter()
constructor(private el: ElementRef, private model: NgModel) {
// To know trim is applied or not. For Testing
//el.nativeElement.style.backgroundColor = 'yellow';
}
@HostListener('change') onInputChange3() {
// no-trim attribute on element will skip the triming.
if (!this.el.nativeElement.noTrim) {
const value = this.el.nativeElement.value.trim();
this.model.viewModel = value;
this.ngModelChange.emit(value);
}
}
}
你可以试试这个。
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { tap } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
control: FormControl;
ngOnInit() {
this.control = new FormControl();
this.control.valueChanges
.pipe(
tap((value) => console.log(value)),
tap((value: string) => this.control.setValue(value.toUpperCase(), {emitEvent: false})
)
)
.subscribe()
}
}
component.html
<input type="text" [formControl]="control">
无需使用Pipe或directived。
只需给输入字段一个类,例如 .myInput
现在就像下面这样装饰它。
.myInput {
text-transform: uppercase;
}