[英]Angular: change value on input event
I have textarea.我有文本区域。 I try to restrict width of value to 10 symbols.
我尝试将值的宽度限制为 10 个符号。 I am trying to cut value on
input
event.我正在尝试削减
input
事件的价值。
<textarea [(ngModel)]="smsMessage" (input)="changeSMSMessage()"></textarea>
changeSMSMessage() {
this.smsMessage = this.smsMessage.substr(0, 10);
console.log(this.smsMessage);
}
But it doesn't work.但它不起作用。 I see that value was cut in
changeSMSMessage()
method, but on UI I see not changed value.我看到该值在
changeSMSMessage()
方法中被削减,但在 UI 上我看到没有改变值。
Plunker笨蛋
When I changed event from input
to keyup
, it starts work properly.当我将事件从
input
更改为keyup
时,它开始正常工作。 All characters after the tenth are deleted.删除第十个之后的所有字符。
So, could someone explain why is input
event doesn't update value in textarea
?那么,有人可以解释为什么
input
事件不更新textarea
中的值吗?
You have several options:您有几种选择:
1 - use the maxlength="10"
tag of the text area: 1 - 使用文本区域的
maxlength="10"
标签:
<textarea [(ngModel)]="smsMessage" maxlength="10"></textarea>
2 - Use a reactive form control with a built-in validator : 2 - 使用带有内置验证器的反应式表单控件:
3 - Control the input: 3 - 控制输入:
<textarea [(ngModel)]="smsMessage" (change)="changeSMSMessage()"></textarea>
// TS
changeSMSMessage() {
this.smsMessage = this.smsMessage.length > 10 ? this.smsMessage.substr(0, 10), this.smsMessage;
}
Use formControl and subscribe to it's valueChanges when your component is initialized, which will allow you to use rxjs operators for advanced requirements like performing http requests, apply a debounce until user finish writing a sentence, take last value and omit previous.使用 formControl 并在您的组件初始化时订阅它的 valueChanges,这将允许您使用 rxjs 运算符来满足高级要求,例如执行 http 请求、应用去抖动直到用户写完一个句子、获取最后一个值并忽略之前的值。
import {Component, OnInit} from '@angular/core';
import { FormControl } from '@angular/forms';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
@Component({
selector: 'some-selector',
template: `
<input type="text" [formControl]="searchControl" placeholder="search">
`
})
export class SomeComponent implements OnInit {
private searchControl: FormControl;
private debounce: number = 400;
ngOnInit() {
this.searchControl = new FormControl('');
this.searchControl.valueChanges
.pipe(debounceTime(this.debounce), distinctUntilChanged())
.subscribe(query => {
console.log(query);
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.