我有一个可以在用户输入时添加和删除冒号的函数,但是输出显示在输入字段之外,因此我试图在输入时更改输入字段。我有以下函数(更改)执行。
这是代码
<mat-form-field>
<input matInput (change)="changedInput()" placeholder="MAC address" name="mac_address" required [(ngModel)]="model.mac_address" (blur)="validate()">
<mat-error *ngFor="let error of errors_by_field['mac_address']">{{error.message}}</mat-error>
<span>{{formatedMac}}</span>
</mat-form-field>
changedInput() {
const blocks = this.model.mac_address.match(/.{1,2}/g);
this.formatedMac = blocks.shift();
for (const block of blocks) {
this.formatedMac = this.formatedMac + ':' + block;
}
}
我如何自定义此选项,以使输入内容随用户类型而变化?
答案 0 :(得分:2)
您使用了[(ngModel)]
,因此您输入的所有内容都将输入model.mac_address
中,并且您在model.mac_address
上进行的每个编程修改都将输入到您的输入中。
然后尝试:
<mat-form-field>
<input matInput (change)="changedInput()" placeholder="MAC address" name="mac_address" required [(ngModel)]="model.mac_address" (blur)="validate()">
<mat-error *ngFor="let error of errors_by_field['mac_address']">{{error.message}}</mat-error>
<span>{{model.mac_address}}</span>
</mat-form-field>
changedInput() {
const blocks = this.model.mac_address.match(/.{1,2}/g);
let formattedMac = blocks.shift();
for (const block of blocks) {
formattedMac = formattedMac + ':' + block;
}
this.model.mac_address = formattedMac;
}