Tips for Wrapping Page Layouts and Routes in Angular 4

As I work with my regular angular 4 app, I often find myself using Router, ActivatedRoute.params.subscribe, [routerLink], and other tools to navigate between pages and interpret URLs.

This results in a multitude of "magic strings" scattered throughout various .ts files. While this approach technically works because the strings match up, it feels messy and intertwined. Here's an example:

<a [routerLink]="['/foo']">Home</a>
 <a [routerLink]="['/foo/item', 1]">Item 1</a>
 <a [routerLink]="['/foo/item', 2]">Item 2</a>

One solution I considered is creating a service dedicated to building URLs for components, thereby centralizing knowledge of the URL structure. However, as someone relatively new to Angular, I'm not sure if using "magic strings" might actually be preferred for some reason.

Is there a recommended best practice for keeping URL structure separate from components?

Answer №1

I have always preferred using the router dependency within my components and manually navigating to each destination. While it may require updating some strings if routes change, I find this method effective for my needs.

In order to visualize the routes of my application, I developed a navigation component. Although I experimented with dynamically constructing application routes using metadata and rights management, it ultimately hindered lazy-loading capabilities, so I do not recommend pursuing that route.

For me, the most efficient approach is creating a navigation component that consumes a single Router configuration (depending on requirements). You can see an example here: https://github.com/akveo/ng2-admin/blob/master/src/app/pages/pages.menu.ts

Additionally, check out the demo app here: https://github.com/akveo/ng2-admin

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mapping an array in Typescript using Angular to instantiate a class

I have received data from a web API that resembles the structure below. I am looking for guidance on how to properly map the product array into individual Products. My main objective is to convert the eating_time values into JavaScript datetime format. Cu ...

Adding the "disabled" attribute to a button using React

I am currently working on a project using Reactjs/nextjs and I need to add or remove the "disable" attribute. Can anyone assist me with this? Below is the code snippet I am working with: const handleSubmit = (e) => { e.preventDefault(); ...

Unable to access the vertical scrollbar in the browser due to a fullscreen fixed bootstrap modal

Bootstrap 4 is being utilized in my current project, where I have made modifications to the modal style to achieve a fullscreen effect. The following CSS code showcases the changes: .modal.show { display:flex!important; flex-direction:column; justi ...

Switching between 3 text options with the click of a button

I am in the process of creating a website and I want to be able to switch between displaying three different text values with the click of a button. Specifically, I am trying to toggle between USD and GBP values for standard and premium fees. Currently, I ...

Sending a variable to a template in AngularJS

I am looking for a way to pass a variable or text to a template in order to display the value within my template. While browsing through resources, I found an example on jsFiddle that demonstrates this functionality using ng-repeat. However, I am curious ...

Unlocking the power of setting global variables and functions in JavaScript

Within my language.js file, the following functions are defined: function setCookie(cookie) { var Days = 30; //this cookie will expire in 30 days var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = coo ...

In Chrome Inspector console, a never-ending JavaScript loop is triggered by a modification in the htaccess file to create pretty URLs, specifically when

Brand new to the world of .htaccess modifications and handling clean URLs. I currently have a php/bootstrap/mysql/javascript page at: http://localhost/modules/posts/questions_all.php. I am interested in redirecting pages such as http://localhost/modules/ ...

The correct pattern must not be matched by ng-pattern

Within the ng-pattern attribute, we can define a specific pattern for a field to match. Is there a way to indicate that the field should NOT match the specified pattern? For instance: <input type="text" ng-pattern="/[*|\":<>[\]{}`()&a ...

Encountering an Issue: Unable to connect with 'ngModel' as it is not recognized as a valid property for 'input' even after importing FormsModule

Despite importing FormsModule in my app.module.ts, I am still encountering the following error message. 'Cannot bind to 'ngModel' since it isn't a known property of 'input' I have thoroughly reviewed similar posts, but unf ...

SuperAgent - Refresh the initial request with a new bearer token upon encountering unauthorized access

Issue: I encountered a problem while attempting to resend my original request using superagent. Here is some pseudo code that I came up with: function retryRequest({ params }) { return superagent.post(url) .set("Authorization", `Bear ...

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

Apply the child's style if the parent's sibling contains the specified class

I am struggling to add the class "bold" to a child element (span) of a parent element (button.usa-nav-link). This parent element has a sibling (ul li.active) with the class .active. When the sibling is active, I want the child element's text to be bol ...

Tips for implementing a default font on a website

I've incorporated a unique font into a specific section of my website design, but I'm aware that this particular font may not be available on most of my users' computers. Is there a method to apply this font to selected text without resortin ...

Leverage the power of JavaScript within your PHP code

For instance, I am looking to use PHP to send an email and my message is obtained from a combination of PHP and JavaScript data... <?php $str= "Data: " . date("Y-m-d H:i:s") . "\n\n"; $str=$str . "system: " . $_SERVER['HTTP_USER ...

Angular 6+ Guards - Utilizing the combineLatest method to return either true or false for subscription

Can the subscribe method in the PermissionsGuard class return true or false? import {Injectable} from '@angular/core'; import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router'; import {AppState} ...

Exploring Attack on Titan alongside the concept of dynamic route templates in coding

I am currently working on creating a factory for an UrlMatcher. export const dummyMatcher: UrlMatcher = matchUrlFn(sitemap as any, 'dummy'); export const routes: Routes = [ { matcher: dummyMatcher, component: DummyComponent }, { path: &apos ...

Initiate an asynchronous request via AJAX from an email address

Has anyone ever tried to send an email with a link that, when clicked, triggers an ajax call to their server? For example, if I sent an email to a Gmail address and the recipient clicked a link in the email, could it make an ajax call to my server? Would ...

What is the process for removing an item from an array that is stored in the backend server?

Apologies for my lack of experience in coding, but I encountered an issue where clicking on the item redirected me to a page and resulted in an error instead of deleting it. I attempted to delete the item using the product ID, but it was not successful. Ev ...

What is the reason behind TypeScript's lack of support for exporting with decorators?

The issue regarding this problem was addressed on https://github.com/tc39/proposal-decorators/issues/69. Despite this discussion, TypeScript does not currently support it. The following code demonstrates the lack of support: export @deco() class a {}; H ...

The compilation time of Webpack and Angular 2

My compile time is currently at 40 seconds and I'm looking for ways to speed it up. I attempted setting the isolatedModules flag to true in the configuration but encountered an error: error TS1208: Cannot compile namespaces when the '--isolated ...