簡體   English   中英

如何在 Angular 中動態更改模板?

[英]How to dynamically change template in Angular?

我有一個渲染樹的通用抽象組件。

我需要能夠根據條件動態更改此組件的模板嗎?

我認為樹邏輯應該在單獨的服務中。 而且我必須使用不同的模板創建兩個組件,使用樹服務,不是嗎?

讓我們假設,我有國家/城市的樹。

在一頁上,我需要在 DOM 結構中顯示:

<div class="root">
    <div class="parent">
       <div class="children"></div>
    </div>
</div>

在另一個頁面中,我需要顯示相同的 DOM,但有一些差異。

  <div class="root">
        <div class="parent">
           <div class="children"><label></label><input></div>
        </div>
    </div>

因此,當然我可以使用一個模板並使用*ngIf來確定顯示/隱藏哪個 DOM 元素。

但我需要分離模板並動態加載它們。

根據變量顯示模板。 要選擇模板,請使用*ngIf 讓我舉個例子:

共享組件的 HTML:

<ng-container *ngIf="showWithoutLabel; else showWithLabel">
    <div class="root">
        <div class="parent">
           <div class="children"></div>
        </div>
    </div>
</ng-container>
<ng-template #showWithLabel>
    <div class="root">
        <div class="parent">
           <div class="children"><label></label><input></div>
        </div>
    </div>
</ng-template>

打字稿:

showWithoutLabel = false;

暫無
暫無

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

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