Implementing Dynamic Views in Angular
In this article, I will show you how to solve a common problem using the Angular way. Imagine that you have a layout like the following:
You have the main navigation and a sidebar that needs to display different content (in our case, links) based on the current route. Let’s see two ways to tackle this in Angular.
Auxiliary Routes
You can think of Auxiliary Routes as extra areas for projecting views into the DOM. We have the primary outlet
, but we can create more outlets
by giving them a unique name. In our case, we need to create a sidebar
outlet.
Now, we can tell our router which component to render based on the URL. To accomplish this, we need to do two things:
- Define the route with the outlet.
2. Navigate to the following location:
http://website.com/route-one(sidebar:route-one-sidebar)
The above syntax activates an Auxiliary route. Let’s break it down.
Inside the parentheses is an auxiliary route. First, we have the name of the outlet to which it refers to: sidebar
.
Then we have a colon separator followed by the URL that we want to apply to that outlet, in this case /route-one-sidebar
. This would cause the RouteOneSidebarComponent
component to render as a sibling to the sidebar
outlet.
The RouteOneSidebarComponent
is a simple component with the view that belongs to this route.
You can use the same process to define the remaining routes. For example:
And the URL for this route will be:
http://website.com/route-one(sidebar:route-two-sidebar)
You can also use the routerLink
directive for navigation.
Structural Directives
A Structural directive changes the DOM layout by adding and removing DOM elements. I’ve already written articles that focus on the following topics, so I’m not going to expand.
First, we need to create a sidebar
component.
We can use the ViewChild
decorator to get a reference to a ViewContainerRef
where we can inject custom templates/components. We also need to be able to use it in our directive, so it needs to be saved in a service.
Let’s add the sidebar
component to our application template.
Next, we need to create the sidebar
directive.
The SidebarDirective
is a structural directive. We are using the sidebar ViewContainerRef
to inject the template as a sibling to the sidebar
container element and then remove it when the component is destroyed.
Now, we can use our directive like this:
Follow me on Medium or Twitter to read more about Angular, Vue and JS!