Last active
June 11, 2023 21:22
-
-
Save AhsanAyaz/5fb84af042a53959a548e256a79b42e6 to your computer and use it in GitHub Desktop.
Popover Positional Class Angular Directive for Angular Cookbook 2nd Edition Recipe
This file contains hidden or 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 { AfterViewInit, ChangeDetectorRef, Directive, Input, OnChanges, Renderer2, SimpleChanges, inject } from '@angular/core'; | |
@Directive({ | |
selector: '[appPopoverPositionalClass]', | |
standalone: true, | |
}) | |
export class PopoverPositionalClassDirective implements AfterViewInit, OnChanges { | |
@Input() originY: string | undefined = 'top'; | |
@Input() targetSelector!: string; | |
@Input() inverseClass = ''; | |
@Input() initialDirection: 'top' | 'center' | 'bottom' = 'bottom'; | |
renderer = inject(Renderer2); | |
cdRef = inject(ChangeDetectorRef); | |
ngAfterViewInit() { | |
this.inverseClass = this.inverseClass || `${this.targetSelector}-inverse`; | |
} | |
ngOnChanges(changes: SimpleChanges) { | |
if (!(changes && changes['originY'])) { | |
return; | |
} | |
if (changes['originY'].currentValue !== changes['originY'].previousValue) { | |
// let the popover appear | |
setTimeout(() => { | |
this.applyClass(changes['originY'].currentValue); | |
}, 0); | |
} | |
} | |
applyClass(originY: 'top' | 'center' | 'bottom') { | |
const target = document.querySelector(this.targetSelector); | |
if (!target) { | |
return; | |
} | |
if (originY !== this.initialDirection) { | |
this.renderer.addClass(target, this.inverseClass); | |
} else { | |
this.renderer.removeClass(target, this.inverseClass); | |
} | |
this.cdRef.markForCheck(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment