简体   繁体   English

如何在 Angular 中动态更改模板?

[英]How to dynamically change template in Angular?

I have a common abstract component that renders tree.我有一个渲染树的通用抽象组件。

I need to able change template for this component dynamically by condition?我需要能够根据条件动态更改此组件的模板吗?

I think tree logic should be in separeted service.我认为树逻辑应该在单独的服务中。 And I have to create two components with different templates, that use tree service, is not?而且我必须使用不同的模板创建两个组件,使用树服务,不是吗?

Lets assume, I have tree of country/cities.让我们假设,我有国家/城市的树。

On one page I need to show that in DOM structure:在一页上,我需要在 DOM 结构中显示:

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

In another page I need to show the same DOM but with some differences.在另一个页面中,我需要显示相同的 DOM,但有一些差异。

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

So, certainly I can use one template and use *ngIf to determine which DOM element show/hide.因此,当然我可以使用一个模板并使用*ngIf来确定显示/隐藏哪个 DOM 元素。

But I need to separate templates and load them dinamically.但我需要分离模板并动态加载它们。

Show template based on variable.根据变量显示模板。 To choose template use *ngIf .要选择模板,请使用*ngIf Let me show an example:让我举个例子:

HTML of shared component:共享组件的 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>

TypeScript:打字稿:

showWithoutLabel = false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM