In this post I will demonstrate how to create a simple treeview using Angular and TypeScript.
I have also created a lazy loaded treview that you can check out here.
Anyway, on to the task at hand!
I created a super basic treeview, but it does highlight some core Angular principles by showing how to render (recursive) templates, add click handlers and basic hide/show logic. In reality, this is probably an 80% use case for most Angular development.
I start out by creating a wrapper component that bootstraps the application and includes the actual treeview component on the page. This sample treeview renders a recursive directory structure with sub directories and files.
I won't go into a lot of details about the specific component syntax since the Angular team has already released pretty good references and samples.
Next I have created the recursive treeview component
The treeview component is included in the main component as <tree-view></tree-view>, but notice in the html for the treeview, there is a self reference. This is important since it's how I am able to render the nodes recursively.
The final piece is an object model for defining the directory structure that gets bound to the treeview
If you're still reading you may have noticed that I purposely define most of the logic in the model class – not in the angular component.
This is conscious choice since it allows me to decouple the core logic from a having a hard dependency on Angular or any other framework for that matter. In the end this is just pure typescript that can be ported to just about any other framework (e.g. Aurelia, Angular 1.x, ReactJS, whatever..).
Another huge benefit of this design is that it's very unit test friendly. A unit test doesn't even have to know that a UI framework is involved.
Here is a screen shot of an unstyled version of the treeview
Here is a live demo.
The code is also available on GitHub, so feel free to check it out.
I also have an article describing a lazy loaded treeview here.