Say, I have a component that accepts ng-content in its template:
but I would like the component to display some default content as a fallback, in case nothing is provided as ng-content. Is there a *ngIf type of directive that I could apply as a test whether ng-content is not empty?
Use the :host /deep/ selector. If you want to use the shadow DOM polyfill and style your components using the style or styleUrls attribute of the Component decorator, select the element with :host , then ignore the shadow DOM polyfill with the /deep/ child selector. :host will select the element.
ng-container serves as a container for elements which can also accept structural directives but is not rendered to the DOM, while ng-template allows you to create template content that is not rendered until you specifically (conditionally or directly) add it to the DOM.
Content projection is a pattern in which you insert, or project, the content you want to use inside another component. For example, you could have a Card component that accepts content provided by another component.
You can check for projected content yourself and show alternative content when none was found:
@Component({
template: `
<div *ngIf="hasContent">alternative content</div>
<div #wrapper>
<ng-content></ng-content>
</div>
`
})
class MyComponent implements AfterContentInit {
@ContentChild('wrapper') wrapper:ElementRef;
hasContent = false;
ngAfterContentInit() {
this.hasContent = this.wrapper.childNodes.length > 0;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With