创建组件模板以多次使用它 - Angular

Create component template to use it multiple times - Angular

这个问题听起来可能很愚蠢,但我还是会尝试一下:

是否可以多次使用一个组件,但内容不同? 类似模板的东西。

准确地说,我只想写一次组件,然后在不同的地方使用它,内容不同——例如(我不知道这是否有任何意义,如果有的话,如何实现它) 通过从分配的模型中获取一些文本来填充 div,这样我可以单独添加更多模型而不是编辑组件本身吗?

一种使用输入将数据传递到组件的方法。

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

然后在组件中您可以使用以下方式获取文本:

@Input() text: Person;

并将其显示在您的模板中

您可以为此使用 ng-content。请找到下面的伪代码

<!-- 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>

利用<ng-content>。插图:

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>

通过使用<ng-content>,您可以将数据从外部 投影到您的 组件内部。您可以通过多种方式使用它,而无需更改原始组件。