1

This question might sound dumb, but I'll try it anyways:

Is it possible to use a component multiple times, but with different content? Something like a template.

To be exact, I want to write the component only once, but then use it in different places with different content - e.g. (I don't know whether that makes any sense and if so, how to realize it) by getting some text from an allocated model to fill a div, so that I can solely add a further model instead of editing the component itself?

1
  • 2
    If I understand you correctly there are several ways you can accomplish this. However, you need to show examples Commented Jun 15, 2019 at 16:08

3 Answers 3

3

Make use of the <ng-content>. Illustration:

app.component.html

<my-component>
   <p>I'm getting projected into a component from outside because of ng-content</p>
</my-component>

my.component.html

<p>Data from my own component</p>
   <ng-content></ng-content>
<p>Data from my own component</p>

By use of the <ng-content> you can project data from outside to within your component. You can make use of this in multiple ways, without changing the original component.

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

Comments

2

One way you can pass data to a component using input.

<my-component [text]="myText"></my-component>

And then in the component you can get the text using:

@Input() text: Person;

And display it in your template

Comments

2

You can use ng-content for this. Please find the below pseudo code

<!-- card.component.html -->
<div class="card">
    <div class="card-header">
        {{ header }}
    </div>

    <!-- add the select attribute to ng-content -->
    <ng-content select="[card-body]"></ng-content>

    <div class="card-footer">
        {{ footer }}
    </div>
</div>

<!-- app.component.html -->

<h1>APP COMPONENT</h1>
<card header="my header" footer="my footer">

    <div class="card-block" card-body><!--  We add the card-body attribute here -->
        <h4 class="card-title">You can put any content here</h4>
        <p class="card-text">For example this line of text and</p>
        <a href="#" class="btn btn-primary">This button</a>
      </div>

<card>

Comments

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.