3

Using Angular-IMask, I'm programatically updating the field that has IMask. So I'm getting the error:

"Element value was changed outside of mask. Syncronize mask using mask.updateValue() to work properly."

I programatically change the input because I have a datepicker associated with it (NgbDatepicker component from Angular-Bootstrap ng-bootstrap module).

How can I get imask object so I can call updateValue() ? I set the component only on the template, so I don't have any object in the component I can access.

Is there any other way to remove that message besides acessing IMask object ? if there is please let me know.

Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73

2 Answers2

2

You can get the IMask instance by querying for the imask directive by using the ViewChild property decorator and then you can access the IMask instance from the directive via the maskRef property.

i.e.

@Component({
  template: `
    <input type="text"
        [imask]="maskConfig"
    >
  `,
})
export class MyMaskComponent {
  maskConfig = {...}

  @ViewChild(IMaskDirective, { static: false })
  iMask: IMaskDirective<IMask.MaskedNumber>;

  ngAfterViewInit(): void {
    this.iMask.maskRef.updateValue();
  }
}
g0rb
  • 2,234
  • 1
  • 9
  • 13
  • Be aware that if you have multiple masked fields in your component, you must use `ViewChildren` instead of `ViewChild` to get a list of all the iMask instance. https://angular.io/api/core/ViewChildren – Willow May 08 '23 at 13:13
-1

You can use ViewChild for this component or use ngOnChanges from Angular LifeCycle and filter for this refeered change to get the current object.

José Lourenço
  • 129
  • 3
  • 4
  • ngOnChanges won't do because I use a datepicker component that doesn't fire onChange on date selection. And if I use ViewChild I would get the input element. There is a way to get the IMask class from the input element ? If it's possible I should be able to get it using document.getElementsByTabName('input')[somenumber]. . I tried and coudn't find any property in the input object that relates to IMask. Do you know how I can get IMask from the input object ? – Nelson Teixeira Apr 06 '22 at 21:11
  • Hi, idk about imask just with ngx mask (idk if you already use this library, but it's pretty useful and its documentation is nice). After the page is loaded, can you get the input element and check on DevTools its class? If the answer is yes, so I think you're not able to get the class by the document selectors because of Angular lifeCycle moments – José Lourenço Apr 06 '22 at 21:43