Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save CharlieGreenman/329f31221fc70a3ff2c6fde88c2df8ed to your computer and use it in GitHub Desktop.
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
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);
}
}
}
}
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