Skip to content

Instantly share code, notes, and snippets.

@OysteinAmundsen
Last active October 16, 2023 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OysteinAmundsen/9e6b2ebdf8264ec0e25a0540661949bc to your computer and use it in GitHub Desktop.
Save OysteinAmundsen/9e6b2ebdf8264ec0e25a0540661949bc to your computer and use it in GitHub Desktop.
Prevent zoom on iOS when input fields are focused
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