簡體   English   中英

創建組件模板以多次使用-Angular

[英]Create component template to use it multiple times - Angular

這個問題聽起來可能很愚蠢,但無論如何我都會嘗試:

是否可以多次使用組件但內容不同? 像模板一樣。

確切地說 ,我只想編寫一次組件,然后在具有不同內容的不同地方使用它-例如(我不知道那是否有意義,如果實現,如何實現)一個分配的模型來填充div,這樣我就可以單獨添加其他模型,而不用編輯組件本身?

利用<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>您可以組件中項目從外部數據。 您可以通過多種方式使用它,而無需更改原始組件。

使用輸入將數據傳遞到組件的一種方式。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM