25

I want create a component like a template. For example, instead of writing this everywhere:

<div class="myClass">
    <div class="myHeader" id="headerId"> Title </div>
    <div class="myContent" id="contentId"> <<Some HTML code>> </div>
</div>

I want to use a component like:

<my-component title="Title" headerID=headerId contentID=contentID>
    <<Some HTML code>>
</my-component>

How can I implement something like these in Angular2?

3
  • 1
    What have you tried? What is the problem? How is <<Some HTML code>> related to the question? Commented Sep 2, 2016 at 12:16
  • 1
    I didn't tried anything since I am not very experienced in Angular2. I googled it but could not find anything similar to what I want. I am looking for suggestions here. Commented Sep 2, 2016 at 12:19
  • So what do you want? What is the desired behavior or result? If you just create a simple component, what does it not do what you want? Commented Sep 2, 2016 at 12:20

1 Answer 1

57

Use <ng-content></ng-content> in your component.

my.component.html

<div class="myClass">
    <div class="myHeader" id="headerId"> Title </div>
    <div class="myContent" id="contentId"> <ng-content></ng-content> </div>
</div>

parent.component.html

<my-component title="Title" headerID=headerId contentID=contentID>
    <<Some HTML code>>
</my-component>

Whatever is inside <my-component></mycomponent> will be rendered in <ng-content></ng-content>

Sign up to request clarification or add additional context in comments.

2 Comments

That's exactly what I want. Thanks!
Is there a way to force lazy loading of content? If I conditinally include <ng-content> in my component, all content gets initialized even if condition is false - eg when contents contains some other components.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.