'Content projection - How to hide another element if the slot is empty?
I am trying to have a container component that uses slots/content projection to push the selected content into a wrapping element. I would like to not render the wrapping element if the selector for the element finds no matching elements.
Example
@Component({
selector: 'app-form-container',
template: /*html*/`
<ng-content select="h1"></ng-content>
<ng-content select="h2"></ng-content>
<div>
<ng-content select="input[type=text]"></ng-content>
<!- custom stuff specific for the text input ->
</div>
<div>
<ng-content select="select"></ng-content>
<!- custom stuff specific for the select input ->
</div>
`,
})
export class FormContainerComponent {
}
My objective is not to render the wrapping div if the selected content isn't provided. For example:
<app-form-container>
<h1>Hello World!</h1>
<input type="text" />
</app-form-container>
Would render as
<app-form-container>
<h1>Hello World!</h1>
<div>
<input type="text" />
<!- custom stuff specific for the text input ->
</div>
</app-form-container>
Omitting the second div designated for the <select> slot
EDIT:
I am currently thinking of running a querySelector on ngAfterViewInit that just checks for each selector and manually deletes the unwanted elements - but that's not very Angular like
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
