任务:在Angular 2中为信用卡动态格式化用户输入。
问题在于,当我删除数字之间的空格时,它会被移除并且不会出现在输入中,尽管导出控制台的值是正确的
我的组件
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
values: any = "";
input_text: string = "10";
tmp: string[] = [];
val: string;
creditCard(event: any) {
if ((/^3[47]\d{0,13}/).test(event.target.value)) {
this.values = "";
this.input_text = this.creditCardType.amex.text_length;
this.val = event.target.value;
this.val = this.val.replace(/[\W\s\._\-]+/g, '');
let chunk = [];
let split = 4;
for (var i = 0, len = this.val.length; i < len; i += split) {
split = ( i >= 4 && i <= 10 ) ? 6 : 4;
chunk.push( this.val.substr( i, split ) );
}
this.values = chunk.join(" ");
console.log(this.values); //after deleting in console: 3456 598756 58745
//on input: 3456 59875658745
}
}
}
app.component.html
<md-input-container>
<input mdInput placeholder="creditCard" (keyup)="creditCard($event)"[value]=values [attr.maxlength]=input_text numbers>
</md-input-container>
<p>{{values}}</p>
我需要无法移除空间,或者在移除后将其显示在输入上。
答案 0 :(得分:1)
而不是 [value] =值尝试 [(ngModel)] ='值'
<md-input-container> <input mdInput placeholder="creditCard" (keyup)="creditCard($event)" [(ngModel)]='values' [attr.maxlength]=input_text numbers>
</md-input-container>
[] - &gt;是单向数据绑定 [()] - &gt;是双向数据绑定