For a Search Engine and Progressive Web Application (PWA) like Loklak, it is important to change the title of each web page with the appropriate query term or configuration of the current active page (A great title can result in higher click-throughs and more traffic to the site, and hence its followed by search engines like Google). For solving this problem, I am writing this blog post which creates a new configuration to change the title dynamically across the whole project by using just one Action thereby maximizing reusability of the code and minimizing duplication.
Create Action for title
We would need to create a new separate title action following the architecture in loklak.
Create a new title.ts file under Actions with the following code:
Create reducer for title
For accessing the current title of the webpage, it is important to create a reducer function for the title following the pattern in loklak.
Create selector and add reducer function to root reducer
The title can be accessed from the current state from store when it would be added to the root state and reducer. Firstly import the title reducer created above and define the title property in root reducer and create a selector for the same.
Create Effect to change actual title
Here the ‘payload’ actually contains the query searched by the user, which will be used update the title.
Note: Before adding a new Effect, the old Effect needs to be removed.
After creating the Effect, add it into app.module.ts and export it in the index.ts.
How to set title using this configuration?
Now comes the interesting part. It becomes very easy to set title from any service or component by following the procedure given below.
- Import the created title action.
- Set the required title by dispatching the SetTitleAction.
You’re all set now! The title has been changed to ‘Loklak Search’ which is what we expect.
- Angular: Platform-Browser
- Angular: state-management
- Loklak Search: Creating Actions using ngrx pattern followed in loklak