Leonard
Leonard

Reputation: 3092

ng-content: transclude the content of the container element, and not the element itself?

I have a modal dialog component based on Bootstrap with three primary child elements: title, summary and footer:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'modal',
  template: `<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title"><ng-content select="header"></ng-content></h4>
      </div>
      <div class="modal-body">
        <ng-content select="summary"></ng-content>
      </div>
      <div class="modal-footer">
        <ng-content select="footer"></ng-content>
      </div>
    </div>
  </div>
</div>`
})
export class ModalComponent {
}

The intention is to simplify the Bootstrap boilerplate:

<modal>
  <header>Hello world!</header>
  <summary>A  message</summary>
  <footer>Dialog footer</footer>
</modal>

Unfortunately, the containing element (header, summary and footer) are also included in the "transclusion," which violates the Bootstrap format. Can I only transclude the container nodes' content?

Upvotes: 4

Views: 3339

Answers (1)

AngularChef
AngularChef

Reputation: 14087

How about wrapping the markup to transclude in <ng-container> elements and using another type of selector to fetch it from <ng-content> (attribute selector, CSS class selector...)?

<ng-container> is supposed to have less interference with existing layout/CSS.

From the consumer's viewpoint:

<modal>
  <ng-container header>Hello world!</ng-container>
  <ng-container class="summary">A  message</ng-container>
</modal>

Inside the modal component's template:

<!-- Attribute selector -->
<ng-content select="[header]"></ng-content>

<!-- CSS class selector -->
<ng-content select=".summary"></ng-content>

Upvotes: 5

Related Questions