I have a question for angular2. I'm creating some components and want to have something like this:
This is my DogComponent class:
@Component({
selector: "dog",
template: "dog.template.html"
})
class DogComponent
{
@Input() image: string;
}
And the template in dog.template.html:
<div>
<!-- Content of <top> should go here -->
<img class="after" src="dogs/{{image}}" />
<!-- Content of <bottom> should go here -->
</div>
When I use the DogComponent, it should create the img-tag with the passed src, but also view the other HTML parts before and after the image.
So in the end, if I write this code:
<dog image="garry.png">
<top>
<h1>This is Garry!</h1>
</top>
<bottom>
<span>He is my favorite dog!</span>
</bottom>
</dog>
it should be rendered to this:
<dog>
<div>
<h1>This is Garry!</h1>
<img src="dog.png" />
<span>He is my favorite dog!</span>
</div>
</dog>
Does someone have the answer to my question?
It would be great!
Edit:
Thanks for the advices, so now I updated my snippets and added the DogListComponent
. The last snippet (Browser result), should be viewed, if I use the tag dog-list
somewhere in my application. Hopefully it's now a little bit clearer.
dog.component.ts
@Component({
selector: "dog",
templateUrl: "dog.template.html"
})
class DogComponent
{
@Input() image: string;
}
dog.template.html
<div>
<!-- Content of <top> should go here -->
<img class="after" src="dogs/{{image}}" />
<!-- Content of <bottom> should go here -->
</div>
dog_list.component.ts
@Component({
selector: "dog-list",
templateUrl: "dog-list.template.html"
})
class DogListComponent
{
}
dog-list.template.html
<dog image="garry.png">
<top>
<h1>This is Garry!</h1>
</top>
<bottom>
<span>He is my favorite dog!</span>
</bottom>
</dog>
<dog image="linda.png">
<top>
<h1>My little Linda :)</h1>
</top>
<bottom>
<span>She is my cutest dog!</span>
</bottom>
</dog>
<dog image="rex.png">
<top>
<h1>And here is Rex!</h1>
</top>
<bottom>
<span>DANGEROUS!</span>
</bottom>
</dog>
Browser result:
<dog-list>
<dog image="garry.png">
<top>
<h1>This is Garry!</h1>
</top>
<bottom>
<span>He is my favorite dog!</span>
</bottom>
</dog>
<dog image="linda.png">
<top>
<h1>My little Linda :)</h1>
</top>
<bottom>
<span>She is my cutest dog!</span>
</bottom>
</dog>
<dog image="rex.png">
<top>
<h1>And here is Rex!</h1>
</top>
<bottom>
<span>DANGEROUS!</span>
</bottom>
</dog>
<dog-list>
So I found my solution! I need to use <ng-content>
.
dog.template.html looks like this:
<div>
<ng-content select="top"></ng-content>
<img class="after" src="dogs/{{image}}" />
<ng-content select="bottom"></ng-content>
</div>
Then it will insert the specified <top>-tags
and <bottom>-tags
in my div.