【发布时间】:2019-09-14 13:12:20
【问题描述】:
我正在构建一个 bin 到 dec 转换器来学习 Angular,但在阻止输入字段接收/显示除 0 或 1 之外的其他数字时遇到了麻烦。
这是我目前所拥有的:
我的组件 html 文件
<form [formGroup]="numberForm">
<input (keyup)="onKey($event)" id="number" placeholder="" value="">
<button (click)="convert()">Convert</button>
</form>
<div class="output">{{ output }}</div>
我的组件 ts 文件
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'app-converter',
templateUrl: './converter.component.html',
styleUrls: ['./converter.component.css']
})
export class ConverterComponent implements OnInit {
numberForm;
values;
output;
constructor(
private formBuilder: FormBuilder
) {
this.numberForm = this.formBuilder.group({
number: ''
})
}
ngOnInit() {}
convert() {
this.output = parseInt(this.values, 2);
}
onKey(event: any) {
console.log(event.target.value);
if((event.keyCode < 48) || (event.keyCode > 49)) {
alert('Only 1 and 0 please!');
return false;
}
this.values = event.target.value;
}
}
这有点像警报消息触发但无效数字仍添加到输入字段,我不知道如何解决这个问题。
我尝试了什么 我曾尝试使用 keyDown 事件,但对于第一次执行,即使我输入了有效数字,console.log(event.target.value) 也会输出 null。
【问题讨论】:
-
请格式化您的代码。
-
@vulp 这样更好吗?
-
有点,但还可以更好。
标签: angular