我有一个函数,可以在用户输入时添加和删除冒号,但输出显示在输入字段之外,因此我尝试在输入时更改输入字段。我有以下功能执行(更改)。
这是代码
<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;
}
}
如何自定义此项以在用户输入时在输入中更改文本?
你使用了[(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;
}