Skip to main content

What you need to know in Angular 10 routing

 

https://damianfallon.blogspot.com/

Angular initial router setup

The Angular router is what makes Angular a Single page application. The browser never refreshes between routes. (Unless you program it as such).

If you have set up the default Angular starter, you will have a file called app-routing.module.ts in your src/app folder.

This one file is responsible for managing our routes.

In there, we have a routes const, in there you see an array of routes, which now looks like this.

const routes: Routes = [
  { path: 'welcome', component: WelcomeComponent }
];
Enter fullscreen mode Exit fullscreen mode

Let's start by adding another route so we can see its effects.

Run the following command in your terminal.

ng generate component second
Enter fullscreen mode Exit fullscreen mode

This will generate a second component.

Now we can add this component in our app-routing.module.ts file.

const routes: Routes = [
  { path: 'welcome', component: WelcomeComponent },
  { path: 'second', component: SecondComponent }
];
Enter fullscreen mode Exit fullscreen mode

Awesome, we can now run our app and manually visit the localhost:4200/welcome and localhost:4200/second.

To run, open terminal, go to the folder, and run ng serve.

Navigating to a route

Now we need to make sure can to navigate to each route from within the application.

To navigate a user to a route, we can use the routerLink on a href.

Let's open our app.component.html (our entry point) and modify it to look like this.

<h1>Our first angular app</h1>
<nav>
  <ul>
    <li><a routerLink="/">Empty homepage</a></li>
    <li><a routerLink="/welcome">Welcome</a></li>
    <li><a routerLink="/second">Second</a></li>
  </ul>
</nav>
<hr />
<router-outlet></router-outlet>
Enter fullscreen mode Exit fullscreen mode

Here we see the router links to our routes and a <router-outlet> that is used to render our actual page in.

So what happens, the top part will always stay, and our welcome and second routes will be opened inside the router-outlet below.

Run this code and click the links. You should see the content change, as you can see in this GIF below.

Fallback routes

As you can see, we are using the router link to / which is not a registered route. We can use fallback routes to catch these unexciting routes.

This also will work if someone manually types /third in their browser.

To set up this wildcard (404) route, we can use the ** for the route.

Let's generate our 404 component to catch all these routes.

ng generate component notFound
Enter fullscreen mode Exit fullscreen mode

Now let's add the route

const routes: Routes = [
  { path: 'welcome', component: WelcomeComponent },
  { path: 'second', component: SecondComponent },
  { path: '**', component: NotFoundComponent }
];
Enter fullscreen mode Exit fullscreen mode

Redirect

Very cool, but we are now also getting this route not found on our initial page localhost:4200/..

What if we want our welcome component to be our main component.

We can add a redirect route.

const routes: Routes = [
  { path: 'welcome', component: WelcomeComponent },
  { path: 'second', component: SecondComponent },
  { path: '',   redirectTo: '/welcome', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent }
];
Enter fullscreen mode Exit fullscreen mode

Here on the third route, we are saying if the main page is called (empty string) we redirectTo the /welcome route.

You will actually see your URL change if you now go to your main page!

Child routes

The last fundamental to Angular routing is the use of child routes.

Image an admin route or a blog-post/category/post setup.
In this case, we will make a child component under the second route.

Let's generate our child component first.

ng generate component child
Enter fullscreen mode Exit fullscreen mode

Then on our routing file, we can add the children element to our second route.

Every element in this children array will be prefixed with he parent route.

const routes: Routes = [
  { path: 'welcome', component: WelcomeComponent },
  { path: 'second', children: [
    { path: '', component: SecondComponent, },
    { path: 'child', component: ChildComponent }
  ] },
  { path: '',   redirectTo: '/welcome', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent }
];
Enter fullscreen mode Exit fullscreen mode

There is a difference in using a component in the parent, we can do this, but then we need another router-outlet in that parent.

We will make use of the same router for all our routes.

Let's now add the link in our app component as well.

<ul>
    <li><a routerLink="/">Empty homepage</a></li>
    <li><a routerLink="/welcome">Welcome</a></li>
    <li><a routerLink="/second">Second</a></li>
    <li><a routerLink="/second/child">-> Second ~ Child</a></li>
</ul>
Enter fullscreen mode Exit fullscreen mode

As mentioned we can also use a second router outlet, let me show you that version as well, let's create an about component for our welcome.

ng generate component about
Enter fullscreen mode Exit fullscreen mode

And add it under our routes.

const routes: Routes = [
  { path: 'welcome', component: WelcomeComponent, children: [
    { path: 'about', component: AboutComponent }
  ] },
  { path: 'second', children: [
    { path: '', component: SecondComponent, },
    { path: 'child', component: ChildComponent }
  ] },
  { path: '',   redirectTo: '/welcome', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent }
];
Enter fullscreen mode Exit fullscreen mode

Now, if we would try and visit this route, we just see the welcome component.

Hmm, weird, right? Well, not really. In this setup we are stating that the main component will have a router-outlet for us to sub render.

Let's open the welcome.component.html file and make it look like this.

<h1>Welcome page</h1>
<a routerLink="/about">About</a>
<hr />
<router-outlet></router-outlet>
Enter fullscreen mode Exit fullscreen mode

If we now run our code and click the about link on our welcome page, we get the following result.

There we go, these are the fundamental elements you will need to know about routing in Angular.

https://damianfallon.blogspot.com/

Comments

Popular posts from this blog

A quarter of users will fall for basic phishing attacks

Slightly more than a quarter of people will fall for a phishing scam that claims to be an urgent message prompting them to change a password, according to statistics gathered by cyber security testing and training firm KnowBe4, which specialises in phishing simulations.
While the statistics might be read as a positive indicator that end-users are awake to the importance of password protection and basic cyber security hygiene, KnowBe4 founder and CEO Sty Sjouwerman said it actually showed the need for users to be even more cautious.
“It is easy to see how they fall for phishing scam related to changing or checking their passwords,” said Sjouwerman. “As identifying phishing attacks from legitimate emails becomes trickier, it is more important than ever for end-users to look for the red flags and think before they click.”
KnowBe4 studied tens of thousands of email subject lines both from simulated phishing tests and those found in the wild, and found many of the most-clicked emails relat…

Coronavirus phishing lures continue to dominate threat landscape

Overall cybercrime activity isn't necessarily going up amid COVID-19, experts say. However, coronavirus-themed emails are becoming the dominant form of phishing attacks. 
The good news is, overall cybercrime isn't necessarily going up significantly amid the COVID-19 pandemic, experts say. The bad news is, coronavirus phishing attacks have become a dominant -- and effective -- threat.
"PhishLabs is not seeing a significant change in attack volumes. What PhishLabs has seen is that COVID-19 has become part of the lure, part of the social engineering mechanism of phishing attacks," PhishLabs founder and CTO John LaCour said. "We're seeing malware attacks, we're seeing credential phishing attacks, we're seeing advance fee fraud/419 scams, we're seeing ransomware, we're seeing all of those things that we see from time to time where attackers are leveraging coronavirus as part of the lure, part of the scam."
LaCour said the type of scams and att…

10 best Content Management Systems of the year

The significant benefits of using a CMS are that such software is often user-friendly. These programs enable users to translate their ideas to practicality quickly. The maintenance and updates are regular and easy to handle. It is highly cost-efficient with out-of-box solutions, freeware or open-source. There is a broad scope for functionality using a large number of extensions and plugins. There is a great developer and community support as well. A Content Management System refers to a software application that can be used for creating and modification of digital content. CMS is generally used for web content management and enterprise content management. ECM (Enterprise Content Management) supports multiple users in a collaborative environment by integrating digital asset management, document management and record retention. Whereas, WCM (Web Content Management) is a collaborative authoring of websites and can include graphics, photos, audio, videos, programmes and maps that display…