我正在尝试修改Angular 4的输入框模型,这样如果用户在框中键入,比如说23,框应该显示23%。
我尝试过在(input)或(change)这样的事件中访问模型值后,将%
附加到模型值中。然而,这完全改变了模型。我想要的是角度模型变量应该仍然包含23,但应该显示23%。
我有没有办法建立一个关于这个的指令。有什么建议或链接吗?
发布于 2017-10-01 17:30:16
这有点老生常谈,但你可以这样做:
<input #input1 value="{{title}}%" (keydown)=setModel(input1.value)>
在组件中:
title = '23';
setModel(val) {
this.title = val.split('%').join('');
console.log(this.title)
};
value="{{title}}%"
将采用title
值,并在末尾添加%
。您可以使用setModel
方法设置新值,但在设置之前,您需要删除所有的%
字符,如:this.title = val.split('%').join('');
。
发布于 2017-10-01 17:36:37
由于您试图更改组件显示值的方式,因此应该使用指令而不是更改模型中的实际值。换句话说,这里需要一个输入掩码。您可以使用现有的包之一(例如https://github.com/text-mask/text-mask)或编写自己的指令。
发布于 2017-10-01 17:39:29
您可以创建一个包含两个值的组件:一个是绑定值,另一个是显示值。该组件看起来有点像这样:
@Component({
selector: 'hello-world',
template: `
<input type="text" [(ngModel)]="display" (keyup)="updateInput($event)" placeholder="Enter a name here">
<hr>
<h1>Input: {{input}}</h1>
`
})
export class HelloWorld {
@Input() input = 0;
@Output() inputChange = new EventEmitter();
display;
ngOnInit() {
this.display = `${this.input}%`
}
updateInput(evt) {
this.input = this.display.replace(/[^0-9.]/g, "");
this.display = `${this.input}%`;
this.inputChange.emit(this.input);
}
}
您可以像这样绑定到组件:
<hello-world [(input)]="myVar"></hello-world>
https://stackoverflow.com/questions/46510870
复制相似问题