Create Custom Tree with Reactive form in Angular

Jitendra Prajapati
ashutec
Published in
2 min readNov 7, 2021

Why did I create a custom tree with reactive from?

I have looked at many npm packages which give tree structure, but none of them give the option to add form elements eg. textbox, checkbox.

For example, we want to create new roles with permission, and permission may have sub permissions, and the user can select permission which he wants to allow for a particular role. Or we may have requirements like creating a restaurant management system and want to display restaurants for add/edit based on states and city. In such types of scenarios, we need to create a tree that supports form in each node. I have created one sample app which allows users to add a new role with permission.

Jitendra Prajapati custom tree with reactive form

Let's create a small app, called the Permission App. Permission App will take the user’s name, role name, and permission in tree format. There is pre-defined permission for reading and writing. While creating a new role user will check permission which user wants to grant.

I will use the reactive form to create form. You can refer to the reactive form here if you are not familiar with the reactive form.

Let's Start to create a Permission App.

Run below command in terminal to create angular project permission app.

ng new permission-app

The next step is to create a permission component where we will define form and tree structure. I have created a permission form group that contains sub form control which will help to take sub permission.

Created permission.component.html.

permission component which creates form and renders tree. I have used two selectors.

1) app-render-node which render the name of the node and form the element for each node.

2) node component which renders children component.

Created RenderNodeComponent which will render each node’s title and form element. This component will get each node info using Input decorator and create a form group

Created RenderNodeComponent.html. To display node title and form for each node. If the node hasn’t children means its last node so we will render a form for that node.

Created NodeComponent.ts to display children node. This component will get node information using an input decorator. NodeComponent will be used reclusively to display each node.

Created NodeComponent html which will render each node name with form details. If the node has children then I have called reclusively this component, so that it renders its children node also.

Let's do some UI stuff, so it looks good.

And finally, call the permission selector in app.component.html to render the permission form.

<permission></permission>

Now our permission is app is ready, we can save/update permissions.

You can also see source code on GitHub or Stackblitz

Note: Please suggest new topics for the blog in Angular in the comment sections.

--

--