2

I have a component A with its html/ts file. When I inherit a second component B from A, this will take all properties and method on the first. If I want to use the component A html, I can reference the comp A html in the templateUrl property.

I have a problem. I want use the component A html, but I want extend it. So my idea is "include" the first component html to the second. It's possible in Angular2? Is there another way?

I don't want to create an instance of component A in the component B. I want only the html markup.

EDIT:

In this example there is my problem:

https://stackblitz.com/edit/ng-content-projection-lzjwea

when I inherited the Hello2 ts, If I create an instance of hello component in hello2 html, it take its name property. I found three solutions:

  1. Change all properties that need to be used in all inherit component to input and inject the
  2. Duplicate html code
  3. Find a way to reference the html of first component without creating an instance of it.

I think the best solution is the third. But I don't know a way to do it..

2
  • Will ng-content (Content Projection) work for you? Commented Dec 12, 2017 at 13:04
  • unfortunally no.. i created a example to show to you the problem in the main post Commented Dec 12, 2017 at 13:44

1 Answer 1

2

ng-content could be used to project dynamic content in a component.

For example, consider the following

hello.component.html

<div id='border'>
    <h1>Base Component</h1>
    <p>ng-content could be used for projecting dynamic content within a component</p>
    <ng-content>
        <!-- Dynamic content goes here -->
    </ng-content>
</div>

So, now whatever that is in between

<hello>
    <!-- dynamic html here -->
</hello>

app.component.html

<hello>
  <div style="border: 2px solid red">
    <h2>Child Component</h2>
    <button id="sample1"> Sample 1 </button>
    <button id="sample2"> Sample 2 </button>
  </div>
</hello>

Example

Hope this helps

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

1 Comment

i know ng-content, but can't resolve my problem. I created a example to show to you my problem. It is in the main problem.

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.