Dynamic Tree Using Angular 2/4

Hello Angular Experts and Beginners, if you really stuck in a situation how to form dynamic tree using  <ul> and <li>. I’m sure that this blog will definitely helps you.

Download Source Code

Step 1: Prequisite you should have a json data in a format as follows.

Step 2: Once you have data create the following structure in your angular project

File: test.json

 

 

Step 3: Creating declaration file for javascript file.

Here we are now creating a declaration file for the javascript file (myscript.js) using Ambients in typescript.

For reference of TypeScript Ambients please follow this post Typescript Ambients

File: myscript.js

File: myscript.d.ts

Step 4: Once declaration file is ready then create component and template and add reference of declaration file in the component

File: app.component.ts

File: template.html

Note: In the below code i’ve created Recursive ng-template. 

  1. #mylst1 is a template reference variable for the ng-template
  2. let-list –> here we are defining a local variable. let is a key word to declare variables in typescript.
  3. ng-container –> It’s a container to group html elements, which is same as ng-include  in AngularJS. For reference please follow the link 
  4. $implicit –> It is used to set the value for our ng-template using context property of ngTemplateOutlet.

File: app.module.ts

File: main.ts

Step 5: Create a html file in src/DynamicTree.html folder

File: DynamicTree.html

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *