Last active
July 12, 2024 21:00
-
-
Save CharlieGreenman/329f31221fc70a3ff2c6fde88c2df8ed to your computer and use it in GitHub Desktop.
Directive to scroll into view. Showing the before and after using input signals
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 { isPlatformBrowser } from '@angular/common'; | |
import { | |
Directive, | |
ElementRef, | |
Inject, | |
OnChanges, | |
PLATFORM_ID, | |
Renderer2, | |
SimpleChanges, | |
input, | |
} from '@angular/core'; | |
function coerceBooleanProperty(value: any): boolean { | |
return value !== null && `${value}` !== 'false'; | |
} | |
@Directive({ | |
selector: '[appScrollIntoView]', | |
standalone: true, | |
}) | |
export class ScrollIntoViewDirective implements OnChanges { | |
appScrollIntoView = input<boolean>(); | |
constructor( | |
@Inject(PLATFORM_ID) private platformId: any, | |
private elementRef: ElementRef, | |
private renderer: Renderer2 | |
) {} | |
ngOnChanges(simpleChange: SimpleChanges) { | |
if (isPlatformBrowser(this.platformId)) { | |
if (coerceBooleanProperty(this.appScrollIntoView())) { | |
setTimeout(() => { | |
this.renderer.addClass(this.elementRef.nativeElement, 'just-added'); | |
(this.elementRef.nativeElement as HTMLInputElement).scrollIntoView({ | |
behavior: 'smooth', | |
block: 'center', | |
}); | |
}, 10); | |
} | |
} | |
} | |
} |
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 { isPlatformBrowser } from '@angular/common'; | |
import { | |
Directive, | |
ElementRef, | |
Inject, | |
PLATFORM_ID, | |
Renderer2, | |
effect, | |
input, | |
} from '@angular/core'; | |
function coerceBooleanProperty(value: any): boolean { | |
return value !== null && `${value}` !== 'false'; | |
} | |
@Directive({ | |
selector: '[appScrollIntoView]', | |
standalone: true, | |
}) | |
export class ScrollIntoViewDirective { | |
appScrollIntoView = input<boolean>(); | |
constructor( | |
@Inject(PLATFORM_ID) private platformId: any, | |
private elementRef: ElementRef, | |
private renderer: Renderer2 | |
) { | |
effect(() => { | |
if (isPlatformBrowser(this.platformId)) { | |
if (coerceBooleanProperty(this.appScrollIntoView())) { | |
this.renderer.addClass(this.elementRef.nativeElement, 'just-added'); | |
(this.elementRef.nativeElement as HTMLInputElement).scrollIntoView({ | |
behavior: 'smooth', | |
block: 'center', | |
}); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment