I have a text box, where I need to change the mask format based on user input and clear the text box. If I change the mask format, the text box is not getting cleared, and if I remove the condition of mask format, the text box is getting cleared
html
<input type="text" mask="{{maskFormat}}" [(ngModel)]="empId" />
<button (click)="toggleMask()">Change Mask</button>
TS
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
maskFormat: string = '000';
empId: string;
toggleMask(): void {
if (this.maskFormat.length == 3) {
this.maskFormat = "000000";
}
else {
this.maskFormat = "000";
}
this.empId = "";
}
}
Note: I am using ngx-mask package
I think it's due to the ngx-mask
module performing some recalculation of the value and then setting the model value after your this.empId = "";
is run.
By adding a setTimeout
function with a zero timer, you will force Angular to wait one life cycle before it set's the value, thus letting the ngx-mask
code run before your code.
setTimeout(() => { this.empId = null }, 0);
This is not an elegant solution but without looking into the ngx-mask
module, it solves your problem.