Skip to content

Support for Dynamic Content Projection #8563

Open
@mhevery

Description

@mhevery

Use Case

<ng-content> allows for static (compile time resolution) projection of content. There are cases where the projection needs to be controlled programmatically. A common example is when the parent component would like to wrap/decorate the child components during projection.

Mental Model

The mental model would be that <ng-content> is for fast static projection, but for dynamic projection one would use a query to get a hold of the child components in the form of ViewRefs which could then be inserted programmatically at any location in the tree.

Possible Solution

  • ContentViewRef extends ViewRef
  • @Content(selector) Provides a way to select direct children content elements using CSS selectors. (This would be after directives such as ngFor would unroll the content, and it would be in the correct order.)
  • This would allow selection of elements rather than directives. These ContentViewRefs could then be reinserted to any ViewContainerRef
  • We would need ngViewOutlet (similar to ngTemplateOutlet).
@Component({
  template: `
  <div *ngFor="let view of allViews">
    <template ngViewOutlet="view"></template>
  </div>
  <ng-content><!-- project non selected nodes, such as text nodes --></ng-content>
`
})
class MySelect {
  @Content('*') allViews: ContentViewRef[];

  // another example
  @Content('my-option') optionViews: ContentViewRef[];
}
@Component({
  selector: 'app',
  template: `
<my-select>
     Option
    <my-option>header</my-option>
    <my-option *ngFor="let item in items">unrolled items {{item}}</my-option>
    <my-option-group>
        <my-option>
            foo <b>bar</b>
            <other-directive />
</my-option>
        <my-separator></my-separator>
        <my-option></my-option>
</my-option-group>
</my-select>
`
})
class App {}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions