After upgrading our project from Angular 8 to Angular 12, I've been facing an issue with accessing the host component reference in the directive.
Here is the original Angular 8 directive code:
export class CardNumberMaskingDirective implements OnInit {
unmaskedValue: string;
constructor(private control: NgControl,
private element: ElementRef,
private _viewContainerRef: ViewContainerRef) {}
ngOnInit() {
this.hide(this.element.nativeElement);
}
@HostListener('focusout', ['$event.target'])
hide(input) {
const host = this._viewContainerRef['_view'].component;
if (host['disableMask'] instanceof Function) {
host['disableMask'](this.control.name);
setTimeout(() => {
this.unmaskedValue = input.value;
const value = input.value.replace(/\s/g, '');
if (value.length > MASKED_LENGTH) {
const formatted = input.value.replace(MASKING_REGEXP, '●●●● ●●●● ●●●● ');
this.control.valueAccessor.writeValue(formatted);
}
}, 0);
}
}
@HostListener('focusin', ['$event.target'])
show(input) {
const host = this._viewContainerRef['_view'].component;
const value = input.value.replace(/\s/g, '');
if (value.length > MASKED_LENGTH) {
this.control.valueAccessor.writeValue(this.unmaskedValue);
}
if (host['enableMask'] instanceof Function) {
host['enableMask'](this.control.name);
}
}
}
In Angular V12, the usage of _view has changed to _hostLView for accessing the component reference. However, even after using
this._viewContainerRef['_hostLView '].component;
, I'm still unable to get the component reference.
I came across a similar question on Stack Overflow and tried the solution provided here, but unfortunately, it didn't work for me as I wasn't able to retrieve the component references. Any suggestions would be greatly appreciated.