By Kevin Mathy
Kevin is a Web Developer at ADNEOM Brussels. He is passionate about the latest technologies and is a real Angular enthusiastic: this passion led him to write his own blog regrouping Angular tips and tricks as well as thoughts and ideas to bring the developers’ work to the next level 👉 https://medium.com/@kmathy. Through this article, Kevin explains how to centralize your layouts with low maintenance.
In an application, we are often faced with designing different layouts between certain pages. There is one layout for the login, another for the administrator, a third for the user, and so on.
And maybe, in the end, you end up with
ngIf’s in your application and as you develop, it starts to become difficult to maintain.
How can we simplify this process? By creating a LayoutModule!
Create your LayoutModule
First, let’s create our LayoutModule:
ng g module layouts
Then, generate your layouts, for example:
ng g component layouts/empty-layout
ng g component layouts/admin-layout
ng g component layouts/sidebar-layout
Note: Don’t forget to import your
In this example, I will use the
app-routing.module.ts to configure the routes to take the layouts and apply them to groups of routes
The key to completing our goal is to use the layout as the basis of our children.
Our routes are ready, but we still have to add the
<router-outlet> in our layout to apply the children’s content
This element allows us to place our content at the desired position in our layout. For example, in the different generated layouts:
You now have everything you need to create different layouts and focus on your content!
Finally, to test our different layouts, let’s generate a new component, TestComponent, and include the content of our AppComponent. This component represents the children of our application.
And don’t forget to only add
<router-outlet> to your AppComponent!
How does it work?
First, when the application starts, AppModule will launch the AppComponent using the bootstrap property in the NgModule.
AppComponent only contains the
router-outlet, so it will delegate the content to the Angular router. In our routing configuration, AppRoutingModule, we group the child components into the different layouts we have created. This makes every child in a layout look the same and we can turn our focus to the content of the child components.