1

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:

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

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

But I need to separate templates and load them dinamically.

4
  • What you are asking is unclear. Can you add some code please? Commented Dec 19, 2019 at 10:39
  • Sure, just a moment, check out again please Commented Dec 19, 2019 at 10:40
  • 2
    Perfect, I believe you can solve it very easily using <ng-template>: blog.angular-university.io/… Commented Dec 19, 2019 at 10:46
  • 1
    Your example look to me like it would be simple to just use *ngIf, like you already mentioned. Does your case get substantionally more difficult? If you add the same things at multiple points, you should put that in a ng-template: "<label></label><input>" in your example. Commented Dec 19, 2019 at 10:49

1 Answer 1

1

Show template based on variable. To choose template use *ngIf. Let me show an example:

HTML of shared component:

<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;
Sign up to request clarification or add additional context in comments.

1 Comment

Similar think I did previously, tree structure data I populate recursively in typescript and depend on scenario I can render front end. So html rendering part is dump terminal and it will render data from typescript.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.