Skip to content

Instantly share code, notes, and snippets.

@hassanjuniedi
Created May 10, 2018 15:25
Show Gist options
  • Save hassanjuniedi/c73617581b1da1c408681233bbba1c38 to your computer and use it in GitHub Desktop.
Save hassanjuniedi/c73617581b1da1c408681233bbba1c38 to your computer and use it in GitHub Desktop.
Angular directive to unwrap HTML tag or unwrap component tag.
import { AfterViewInit, Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appUnwraptag]',
})
export class UnwrapTagDirective implements AfterViewInit {
constructor(private el: ElementRef) {}
ngAfterViewInit() {
// get the element's parent node
const parent = this.el.nativeElement.parentNode;
// move all children out of the element
while (this.el.nativeElement.firstChild) {
parent.insertBefore(this.el.nativeElement.firstChild, this.el.nativeElement);
}
// remove the empty element
parent.removeChild(this.el.nativeElement);
}
}
/*
Example of use:
<app-store-widget appUnwraptag [widgetStore]="storeInstance"></app-store-widget>
the result will be the inner html of app-store-widget.
*/
@lmeijdam
Copy link

lmeijdam commented Dec 4, 2020

man i have searched for an elegant solution similar to this for 3 full days, thanks!

@imarks-saisudhakar
Copy link

Thank you very much, it saves my time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment