Skip to content

Instantly share code, notes, and snippets.

@leye0
Last active December 11, 2019 17:39
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 leye0/aab4c48a72676634a50ced05fcf82d7f to your computer and use it in GitHub Desktop.
Save leye0/aab4c48a72676634a50ced05fcf82d7f to your computer and use it in GitHub Desktop.
Angular - Directive - Add a class to an element if the element is contained within an element specified by a selector
import { Directive, Input, OnChanges, SimpleChanges, ElementRef } from '@angular/core';
@Directive({
selector: '[isContainedWithin]'
})
export class IsContainedWithinDirective implements OnChanges {
@Input() isContainedWithin: string = '';
@Input() classToAdd: string = '';
constructor(private element: ElementRef) {}
ngOnChanges(changes: SimpleChanges): void {
if (!this.element) { return; }
if (changes.isContainedWithin) {
const htmlElement = <HTMLElement>this.element.nativeElement;
const parent = htmlElement.closest(this.isContainedWithin);
if (this.classToAdd) {
if (parent) {
htmlElement.classList.add(this.classToAdd);
} else {
htmlElement.classList.remove(this.classToAdd);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment