我是Angular5的新手 . 玩弄绑定 .
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `Title : <input type="text" [(ngModel)]="title" (ngModelChange)="onchange(title)" > {{newtitle}}`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = "app";
newtitle = "";
onchange(title:any){
if(title.length < 5){
this.newtitle = "hello "+title;
}
}
}
当ngModel发生变化时,ngModelchange与newtitle变量完全绑定,并使用条件,即长度<5 .
现在我的问题是,我想控制输入框内输入文本的长度 . 我希望输入框不允许用户输入长度> 5 .
我希望它适用于type =“number”,对于字符串,它适用于我的maxlength属性 .
2 回答
据我所知,当长度超过5时,您希望限制输入的输入 . 使用验证器
max
和min
,您可以控制错误消息,但不能阻止输入更多数字 . 而是在ngModelChange
事件中使用keypress
事件 . 在该事件中,方法将拦截任何按键,如果模型值大于99999(因此长度> 5),则它将阻止其默认行为 . 检查其数值非常重要:HTML:
Typescript:
Demo
您可以使用 maxlength 并设置为4:
对于基于数字的输入:
DEMO