Prevent zoom on iOS when input fields are focused
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, HostListener, signal } from '@angular/core'; | |
@Directive({ selector: '[flxInput]', standalone: true }) | |
export class PreventZoomDirective { | |
zoomDisabled = signal(false); | |
hasFocus = signal(false); | |
get meta() { | |
return Array.from(document.getElementsByTagName('meta') || []).find(m => m?.getAttribute('name') === 'viewport'); | |
} | |
@HostListener('pointerover') | |
zoomDisable() { | |
const content = this.meta?.getAttribute('content'); | |
if (!this.zoomDisabled() && content != null) { | |
this.meta?.setAttribute('content', `${content}, maximum-scale=1`); | |
this.zoomDisabled.set(true); | |
} | |
} | |
@HostListener('pointerout') | |
pointerOut() { | |
if (!this.hasFocus() && this.zoomDisabled()) { | |
// Pointer moved out of the input without focus being added. | |
this.zoomEnable(); | |
} | |
} | |
@HostListener('focus') | |
focus() { | |
this.zoomDisable(); | |
this.hasFocus.set(true); | |
} | |
@HostListener('blur') | |
zoomEnable() { | |
const content = this.meta?.getAttribute('content'); | |
if (this.zoomDisabled() && content != null) { | |
this.meta?.setAttribute('content', `${content.replace(', maximum-scale=1', '')}`); | |
this.zoomDisabled.set(false); | |
this.hasFocus.set(false); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment