Recently our project is upgraded from Angular 8 to Angular 12, since then I am unable to access the host component reference in the directive
Below is my directive in Angular 8
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 we don't have _view and I have to use _hostLView to access the component reference. But still I don't get component reference in case I use this._viewContainerRef['_hostLView '].component;
I found a similar one here but the solution posted here https://stackoverflow.com/a/69706978 is not working for me (I was not getting the component references) Any suggestions are much appreciated