Angular does not support optional host-element officially so we should stick to annoying div which sometimes destroys our component design especially for 3rd party CSS frameworks like Bootstrap.
Solution
There is a trick to achieve a no-host component:
import {
AfterViewInit,
Component,
ElementRef,
OnInit,
TemplateRef,
ViewChild,
ViewContainerRef
} from '@angular/core';
@Component({
standalone: true, // or false
selector: 'my-nohost-component',
// Keep the same structure is necessary.
// Put any component's detail inside 'ng-template'.
// You can use 'templateUrl' too but with the same structure.
template: '<ng-template #nohost>HERE!</ng-template>',
})
export class MyNoHostComponent implements OnInit, AfterViewInit {
constructor(
private readonly element: ElementRef,
private readonly viewContainer: ViewContainerRef
) {}
@ViewChild('nohost', { static: true }) noHostRef: TemplateRef<{}> | undefined;
ngOnInit(): void {
if (this.noHostRef)
this.viewContainer.createEmbeddedView(this.noHostRef);
}
ngAfterViewInit(): void {
this.element.nativeElement.remove();
/* Another way
document
.querySelectorAll(this.elem.nativeElement.tagName.toLowerCase())
.forEach((el) => el.parentNode.removeChild(el));
*/
}
}
Usage
This snippet code ngx-nohost helps you write your no-host components faster. Install from here.