Angular2: replace host element with component's template

Denis Itskovich picture Denis Itskovich · Mar 1, 2016 · Viewed 27.3k times · Source

I'm new to angular in general and to angular2 specifically. I'm trying to write a container component, which should have child components in it.

For example, container component:

@Component({
  selector: 'my-list',
  template: `
    <ul>
      <ng-content></ng-content>
    </ul>
  `
})
export class MyList {
}

Child component:

import { Component } from 'angular2/core'

@Component({
  selector: 'my-item',
  template: `
    <li>
      <ng-content></ng-content>
    </li>
  `
})
export class MyItem {
}

I'd like to make this structure:

<my-list>
    <my-item>One</my-item>
    <my-item>Two</my-item>
</my-list>

To be rendered to the following one:

<my-list>
    <ul>
        <li>One</li>
        <li>Two</li>
    </ul>
</my-list>

But instead, I have the host element of the container and the items preserved as well:

<my-list>
    <ul>
        <my-item>
            <li>One</li>
        </my-item>
        <my-item>
            <li>Two</li>
        </my-item>
    </ul>
 </my-list>

Plunk is available here

Question: is there a way to eliminate the host elements and to leave only the rendered template?

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Mar 1, 2016

This you should get what you want:

@Component({
  selector: 'ul[my-list]',
  template: `
    <ng-content></ng-content>
  `
})
export class MyList {
}
@Component({
  selector: 'li[my-item]',
  template: `
    <ng-content></ng-content>
  `
})
export class MyItem {
...
}
<ul my-list>
    <li my-item>One</li my-item>
    <li my-item>Two</li my-item>
</ul my-list>