https://github.com/hamedfathi/angular-nohost-vscode-snippet
A no-host component snippet code for Angular 2+ and Microsoft Visual Studio Code.
https://github.com/hamedfathi/angular-nohost-vscode-snippet
angular angular2 snippet snippets vscode vscode-extension vscode-snippets
Last synced: about 2 months ago
JSON representation
A no-host component snippet code for Angular 2+ and Microsoft Visual Studio Code.
- Host: GitHub
- URL: https://github.com/hamedfathi/angular-nohost-vscode-snippet
- Owner: HamedFathi
- License: mit
- Created: 2022-08-01T15:50:02.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2024-03-17T17:49:07.000Z (over 2 years ago)
- Last Synced: 2025-01-13T23:13:11.542Z (over 1 year ago)
- Topics: angular, angular2, snippet, snippets, vscode, vscode-extension, vscode-snippets
- Homepage:
- Size: 18.6 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README

## Problem
Angular does not support [optional host-element](https://github.com/angular/angular/issues/18877) 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:
```typescript
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: 'HERE!',
})
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](https://marketplace.visualstudio.com/items?itemName=hamedfathi.angular-nohost).
