Angular2: replace host element with component's template
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>
Finally I found solution: injecting ElementRef
to MyItem
and using its nativeElement.innerHTML
:
MyList:
import { Component, ContentChildren, QueryList } from 'angular2/core'
import { MyItem } from './myitem'
@Component({
selector: 'my-list',
template: `
<ul>
<li *ngFor="#item of items" [innerHTML]="item.innerHTML"></li>
</ul>
`
})
export class MyList {
@ContentChildren(MyItem) items: QueryList<MyItem>
}
MyItem:
import { Directive, Inject, ElementRef } from 'angular2/core'
@Directive({selector: 'my-item'})
export class MyItem {
constructor(@Inject(ElementRef) element: ElementRef) {
this.innerHTML = element.nativeElement.innerHTML
}
}
Working plunk is here
New angular versions have really cool directive, which may be used also for your use case. Tadaa: NgComponentOutlet. Happy coding ;)
Example:
@Component({selector: 'hello-world', template: 'Hello World!'})
class HelloWorld {
}
@Component({
selector: 'ng-component-outlet-simple-example',
template: `<ng-container *ngComponentOutlet="HelloWorld"></ng-container>`
})
class NgTemplateOutletSimpleExample {
// This field is necessary to expose HelloWorld to the template.
HelloWorld = HelloWorld;
}