Angular Forms Routes with Child Nodes and Wildcard
Angular Forms Routes with Child Nodes and Wildcard
Nested Routes/ Child Routes
The Components follows a Tree structure, where we have a root component at the top. We can then add child components forming loosely coupled components resembling a Tree. The Routes in Angular also follows the component tree structure and allows us to define the nested or child routes.
In the above example, the ProductComponent displays the list of Products. The ProductDetailsComponent is defined as the child of the ProductComponent displays the details of the selected Product. So Our routes would be /Product and /Product/Details/:Id
v Steps to create Nested Routes/Child Routes:
We already have created ProductDetailsComponent, but it is not designed as the child route of the ProductComponent. Let us update the code make it child route of the Product route.
1. Define the Routes:
ü Open the app.routing.ts file
ü You will see the following routes defined in our application.
ü Here the ProductDetailComponent is defined as the sibling of the ProductComponent and not as the child
{ path: ‘product’, component: ProductComponent },
{ path: ‘product/:id’, component: ProductDetailComponent
},
ü To make ProductDetailComponent as the child of the ProductComponent, we need to add the children key to the product route, which is an array of all child routes as shown below
|
{ path: ‘product’, component: ProductComponent, children:[ { path: ‘detail/:id’, component: ProductDetailComponent } ],
|
The child route definition is similar to the parent route definition. It has a path and component that gets invoked when the user navigates to the child route. In the above example, the parent route path is ‘product’ and the child route is ‘detail/:id’.
This is will match the URL path “/product/detail/id”. When the user navigates to the “/product/detail/id”, the router will start to look for a match in the routes array. It starts of the first URL segment that is ‘product’ and finds the match in the path ‘product’ and instantiates the ProductComponent and displays it in the <router-outlet> directive of its parent component ( which is AppComponent) The router then takes the remainder of the URL segment ‘detail/id’ and continues to search for the child routes of Product route. It will match it with the path ‘detail/:id’ and instantiates the
ProductDetailComponent and renders it in the <router-outlet> directive present in the ProductComponent Final app.routing.ts looks like this;
import { Routes }
from ‘@angular/router’;
import {HomeComponent} from ‘./home.component’
import {ContactComponent} from ‘./contact.component’
import {ProductComponent} from ‘./product.component’
import {ErrorComponent} from ‘./error.component’
import {ProductDetailComponent} from ‘./product-detail.component’
export constappRoutes: Routes = [
{path: ‘home’, component: HomeComponent },
{path: ‘contact’, component: ContactComponent },
{ path: ‘product’, component: ProductComponent,
children:[ {path: ‘detail/:id’, component: ProductDetailComponent } ]
},
{path: ”, redirectTo: ‘home’, pathMatch: ‘full’ },
{path: ‘**’, component: ErrorComponent }];
2. Display the component using Router-outlet
The components are always rendered in the <RouterOutlet> of the parent component. For ProductDetailComponent the parent component is ProductComponent and not the AppComponent. Hence, we need to add <router-outlet></router-outlet> in the product.component.html;
<h1>Product
List</h1>
<div class=‘table-responsive’>
<table
class=‘table’>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr *ngFor=“let product of products;”>
<td>{{product.productID}}</td>
<td><a [routerLink]=“[‘detail’,product.productID]”>{{product.name}}</a> </td>
<td>{{product.price}}</td>
</tr>
</tbody>
</table>
</div>
<router-outlet></router-outlet>
There is no change in the Product Detail Component.
import {Component, OnInit } from ‘@angular/core’;
import {Router,ActivatedRoute } from ‘@angular/router’;
import {ProductService } from ‘./product.service’;
import { Product }from ‘./product’;
@Component({
templateUrl:
‘./product-detail.component.html’,
})
export class
ProductDetailComponent
{product:Product;
id;
sub;
constructor(private _Activatedroute:ActivatedRoute,
private _router:Router,
private _productService:ProductService){
}
ngOnInit() {
this.id=this._Activatedroute.snapshot.params[‘id’];
let products=this._productService.getProducts();
this.product=products.find(p => p.productID==this.id);
}
}
Note that we are using the snapshot method to retrieve the route parameter id.
3. Testing the Nested/Child Route:
Run the app and click on the Product link. You will see that the Product Page is displayed. Click on any of the Product, and you will see the Product details page is displayed.
v Redirecting and Wildcard routes:
When the application start, it navigates to the empty route by default. We can configure the router to redirect to a named route by default. So, a redirect route translate the initial relative URL(‘ ‘) to the desired default path. For example, if we may want to redirect to Login page or Registration page by default when the application start, then you need to configure the redirectTo like;
This route redirects a URL that fully matches the empty path to the route whose path is ‘/Login’. The empty path in the first route represents the default path for the application. This default route redirects to the route for the /Login URL and therefore will display the Login Component.
A redirect route requires a pathMatch property to tell the router how to match a URL to the path of a route. The router throws an error if you don’t. For the special case of an empty URL we also need to add the pathMatch: ‘full’ property so angular knows it should be matching exactly the empty string and not partially the empty string.
E.g: Redirecting using Student Login example
Let us understand the concept Redirecting Route with an example. In order to understand this we are going to create a component called Login Component.
ü So, open terminal and then type ng g c Login and press enter as shown in the below image.
ng generate component Login
Once you press enter button it will create a component called Login and inside that component it will creates four files like ;
ü Modify app.component.html file
<a [routerLink] = “[‘/studentLink’]” >Student</a> <br/>
<a [routerLink] = “[‘/studentdetailsLink’]” >student details</a><div>
<router-outlet></router-outlet></div>
ü Modify app.component.ts file
At this point, if you run the application, then you will get the following output. If you notice the URL it is empty and displaying default page.
Instead of showing the default page when the URL is empty, we want to redirect to the Login page. Now, redirecting routes will comes into picture like;
ü Modifying the app.routing.module.ts file- Open app-routing.module.ts file and then copy and paste the following code in it. Here, we did three things. First import the login component. Second create a path for login component and finally create an empty path and set redirectTo property value to the login path.
import { NgModule } from ‘@angular/core’;
import { Routes, RouterModule } from ‘@angular/router’;
import { StudentComponent } from ‘./student/student.component’;
import { StudentdetailComponent } from ‘./studentdetail/studentdetail.component’;
import { LoginComponent } from ‘./login/login.component’;
const routes: Routes = [
{path:”, redirectTo:’Login’,pathMatch:’full’},
{path:’studentLink’, component:StudentComponent},
{path:’studentdetailsLink’, component: StudentdetailComponent},
{path:’Login’, component:LoginComponent}];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]})
export class AppRoutingModule { }
With the above changes in file, now run the application. Go to the default URL. i.e. https://localhost:4200 it will automatically redirect to the Login page like;
v Wildcard Route:
The Wildcard Route is basically used in Angular Application to handle the invalid URLs. Whenever the user enter some invalid URL or if you have deleted some existing URL from your application, then by default 404 page not found error page is displayed. In such scenarios instead of showing the default error page, if you also show a custom error page and this is possible by using the Angular Wildcard Route.
ü How to use Wildcard Route?
A Wildcard route has a path consisting of two asterisks (**). It matches every URL, the router will select this route if it can’t match a route earlier in the configuration. A Wildcard Route can navigate to a custom component or can redirect to an existing route. The syntax to use Wildcard Route is given below.
ü Steps to use Wildcard Route:
· First, create a new component customererror
· Now, open customererror.component.html file and type <h1> The page does not exist </h1>
· Now, open app-routing.module.ts file and update it with following code;
import { NgModule } from ‘@angular/core’;
import { Routes, RouterModule } from ‘@angular/router’;
import { StudentComponent } from ‘./student/student.component’;
import { StudentdetailComponent } from’./studentdetail/studentdetail.component’;
import { LoginComponent } from ‘./login/login.component’;
import { CustomerrorComponent } from ‘./customerror/customerror.component’;
const routes: Routes = [
{path:”, redirectTo:’Login’,pathMatch:’full’ },
{path:’studentLink’, component:StudentComponent },
{path:’studentdetailsLink’, component: StudentdetailComponent },
{path:’Login’, component:LoginComponent},
{path:’**’, component:CustomerrorComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
· Next, we need to create one invalid link.
· Open, app.component.html file and write the following invalid link
<h2>Angular Routing Example</h2>
<a [routerLink] = “[‘/studentLink’]” >Student</a> <br/>
<a [routerLink] = “[‘/studentdetailsLink’]” >student details</a><br/>
<a [routerLink] = “[‘/invalidLink’]” >Invalid Link</a>
<div>
<router-outlet></router-outlet>
</div>
· Now save all the change and open the browser and click on the Invalid link and you should see the custom error message as shown in the below image.
I savour, cause I discovered exactly what I used to be looking for. You’ve ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye