Routing From One To Other Component


 Routing from One to Other Component

1. Routing from HTML DOM Element's (View)

1. routerLink is an angular directive which take's route of 
other component as a value.
2. This routerLink can be used either on button or anchor tag.

<a routerLink="/ANY_PATH">....</a> OR <a [routerLink]="['PATH']">...</a>

From Previous section of this blog see all the route's and example of route's we have created.
        (https://angularprogrammer.blogspot.com/2018/10/advanced-routing-in-angular-6.html

In template-forms.html 

<a routerLink="/list">Navigate to list</a>

1. When user click's on the above link it navigate's the user to 
   list component and renders the list component.

2. Routing from Controller

1. Angular has provided a service called Router Service 
  present in Router Module. 
2. import Router Service in your component as follow's 
    import { Router } from '@angular/router';
3. Now the imported Router Service need to be injected in the 
   constructor of the component as below. 
   constructor(private _router: Router) {}
4. Now by using _router reference we can use all the method's 
   provided by Router Service.
5. For now to navigate we can use navigate or navigateByUrl method's
   to navigate from one path to other path.
6. navigate method take's array of path's and sub-path's and navigate's
   where as navigateByUrl will take the path in URL format 

In template-forms.component.ts

import { Component, OnInit } from '@angular/core';

import {Router} from '@angular/router';

@Component({
  selector: 'app-template-forms',
  templateUrl: './template-forms.component.html',
  styleUrls: ['./template-forms.component.css']
})
export class TemplateFormsComponent implements OnInit {

  constructor(private _router: Router) { }

  ngOnInit() {
  }
  navigateToList() {
    this._router.navigate(['list']);
        OR
    this._router.navigate(['/list']);
  }
}

In template-forms.component.html

<button (click)="navigateToList()">
    Navigate to list page from Controller
</button>

1. When user click on the above button click event will be 
   generated and call's navigateToList method which is 
   declared and defined in the controller and will execute the 
   navigate method then if it find's the exact path in the route's array ,
   that particular component will be rendered.
  



Note

1. Before using router service make sure to import RouterModule 
   in the parent module of the component.
2. If you don't have seperate routing file then Import as follow's 
   in module file.
    import { RouterModule } from '@angular/router';

    @ngModule({imports: [
      RouterModule.forRoot(appRoutes);
    ]});
3. If you have routing file seperatly then simply import the 
   RoutingFile into your module. No need to follow POINT 2.

Comments

Popular posts from this blog

MVC or MVVC Pattern In Angular

Angular 6 Template Driven Form Validations

7. Class Binding