Thursday, 24 November 2022

Angular #4 Routing

Angular 19 Routing - Step-by-Step Guide with Code 🚀

📌 What is Routing in Angular?

Routing allows navigation between different components without refreshing the page. It helps create Single Page Applications (SPAs).


🔹 Step 1: Create a New Angular App

ng new angular-routing-example --standalone

📌 Flags Used:

  • --standalone: Creates the app using Standalone Components (Angular 16+).

🔹 Step 2: Generate Components

cd angular-routing-example
ng g c home --standalone
ng g c about --standalone

📌 This creates two components:

  • HomeComponent (home.component.ts)
  • AboutComponent (about.component.ts)

🔹 Step 3: Define Routes in app.routes.ts

Create a new file:
📌 src/app/app.routes.ts

import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

export const routes: Routes = [
  { path: '', component: HomeComponent }, // Default Route
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
];

📌 Explanation:

  • '/' → Loads HomeComponent by default.
  • '/home' → Navigates to Home page.
  • '/about' → Navigates to About page.

🔹 Step 4: Update app.component.ts

📌 Modify app.component.ts

import { Component } from '@angular/core';
import { RouterModule } from '@angular/router';
import { routes } from './app.routes';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterModule.forRoot(routes)],  // ✅ Import RouterModule with routes
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {}

🔹 Step 5: Add Navigation Links in app.component.html

📌 Modify app.component.html

<nav>
  <a routerLink="/home">Home</a> |
  <a routerLink="/about">About</a>
</nav>

<router-outlet></router-outlet>

📌 Explanation:

  • <a routerLink="/home"> → Clicking navigates to /home.
  • <a routerLink="/about"> → Clicking navigates to /about.
  • <router-outlet></router-outlet> → Loads the respective component.

🔹 Step 6: Run the Application

ng serve

📌 Open http://localhost:4200 in your browser.

  • Click Home → Loads HomeComponent.
  • Click About → Loads AboutComponent.

🎯 Final Folder Structure

angular-routing-example/
│── src/
│   ├── app/
│   │   ├── app.component.ts
│   │   ├── app.component.html
│   │   ├── app.routes.ts  ✅ Routes File
│   │   ├── home/
│   │   │   ├── home.component.ts
│   │   │   ├── home.component.html
│   │   ├── about/
│   │   │   ├── about.component.ts
│   │   │   ├── about.component.html

🔥 Conclusion

✅ Now, you have a fully functional Angular Routing Example!
✅ Clicking the Home and About links will load different pages.
🚀 Happy Coding! 😎

Let me know if you need more help, bro!



Angular Routing Guide for Angular <16

Setting Up Routing in Angular

Follow these steps in the command prompt:

  1. Create a new Angular project

    ng new router-example --standalone
    
    • Select Y for Routing
    • Choose CSS for the stylesheet
  2. Navigate into the project directory

    cd router-example
    
  3. Generate components

    ng g c student
    ng g c subject
    
  4. Open the project

    code .
    

    (Or open the folder manually in VS Code)

  5. Modify app.module.ts

    Open src/app/app.module.ts and update the imports array:

    import { RouterModule } from '@angular/router';
    
    @NgModule({
      imports: [
        BrowserModule,
        RouterModule.forRoot([
          { path: 'student', component: StudentComponent },
          { path: 'subject', component: SubjectComponent },
        ]),
      ],
    })
    
  6. Modify app.component.html

    Delete existing content and replace with:

    <app-student></app-student>
    <app-subject></app-subject>
    
  7. Run the project

    ng serve
    

    Open http://localhost:4200 in a browser to check if the app is working.

Adding Navigation

  1. Modify app.component.html

    <nav>
      <a class="button" routerLink="/student">Student List</a> |
      <a class="button" routerLink="/subject">Subject List</a>
    </nav>
    <router-outlet></router-outlet>
    
    • This will add navigation buttons for Student and Subject.
  2. Modify app.component.css

    .button {
        background: linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);
        border-radius: 6px;
        border: 1px solid #dcdcdc;
        cursor: pointer;
        color: #666;
        font-size: 15px;
        font-weight: bold;
        padding: 6px 24px;
        text-decoration: none;
    }
    
    .activebutton {
        background: linear-gradient(to bottom, #bddbfa 5%, #80b5ea 100%);
        border: 1px solid #84bbf3;
        color: #fff;
    }
    

Displaying Data in Components

  1. Modify subject.component.ts

    export class SubjectComponent {
      subjects = [
        { id: 12, name: 'Networks' },
        { id: 13, name: 'C' },
        { id: 14, name: 'C++' },
        { id: 15, name: 'Angular' },
        { id: 16, name: 'React' },
        { id: 17, name: 'Java' },
        { id: 18, name: 'Python' },
        { id: 19, name: 'HTML' },
        { id: 20, name: 'CSS' }
      ];
    }
    
  2. Modify student.component.ts

    export class StudentComponent {
      students = [
        { id: 102, name: 'Dr. Nice' },
        { id: 103, name: 'Bombasto' },
        { id: 104, name: 'Celeritas' },
        { id: 105, name: 'Magneta' },
        { id: 106, name: 'RubberMan' },
        { id: 107, name: 'Dynama' },
        { id: 108, name: 'Dr. IQ' },
        { id: 109, name: 'Magma' },
        { id: 200, name: 'Tornado' }
      ];
    }
    
  3. Modify subject.component.html

    <div *ngFor="let s of subjects">
      <div style="color: blue">
        {{s.id}}: {{s.name}}
      </div>
    </div>
    
  4. Modify student.component.html

    <div *ngFor="let s of students">
      <div style="color: blue">
        {{s.id}}: {{s.name}}
      </div>
    </div>
    

Final Testing

  • Run ng serve and open http://localhost:4200 to verify the output.

Exercise

  1. Modify app.component.css with:

    .button {
        box-shadow: inset 0 1px 0 0 #ffffff;
        background: linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);
        border-radius: 6px;
        border: 1px solid #dcdcdc;
        display: inline-block;
        cursor: pointer;
        color: #666;
        font-size: 15px;
        font-weight: bold;
        padding: 6px 24px;
        text-decoration: none;
    }
    
    .activebutton {
        background: linear-gradient(to bottom, #bddbfa 5%, #80b5ea 100%);
        border: 1px solid #84bbf3;
        color: #ffffff;
    }
    
  2. Modify the first <a> tag in app.component.html:

    <a class="button"
       routerLink="/student"
       routerLinkActive="activebutton"
       ariaCurrentWhenActive="page">Student List</a> |
    

Check the browser output to see the updated navigation. Happy Learning Angular! 🚀



Actual Hands on Output:

Navigation in Angular is done by Routing

Please follow these steps in command prompt:

1. ng new router-example   Select y for Routing and CSS for stylesheet.

2. cd  router example

3. ng g c student

4. ng g c subject

5. code . (or) Open the folder router-example manually 

6. In VS code editor, open the app.module.ts file.

7.

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

Locate @NgModule() section replace imports array with the following and save: 

 imports: [
    BrowserModule,
    RouterModule.forRoot([
      {path: 'student', component: StudentComponent},
      {path: 'subject', component: SubjectComponent},
    ]),
  ],

8. Open file app.component.html. add and save

Delete the old contents. add  and save:

<app-student></app-student>

<app-subject></app-subject>

open New Terminal Window and type 

ng serve

open in browser http://localhost:4200

:to check the app is working .

9. Open file app.component.html. add the following and save

<nav>
  <a class="button" routerLink="/student">Student List</a> |
  <a class="button" routerLink="/subject">Subject List</a>
 </nav>
<router-outlet> </router-outlet>

Check the Browser output to see as navbuttons.

10. open the app.component.css. Add the following and save:

.button {
    box-shadow: inset 0 1px 0 0 #ffffff;
    background: #ffffff linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);
    border-radius: 6px;
    border: 1px solid #dcdcdc;
    display: inline-block;
    cursor: pointer;
    color: #666666;
    font-family: Arial, sans-serif;
    font-size: 15px;
    font-weight: bold;
    padding: 6px 24px;
    text-decoration: none;
    text-shadow: 0 1px 0 #ffffff;
    outline: 0;
}

.activebutton {
    box-shadow: inset 0 1px 0 0 #dcecfb;
    background: #bddbfa linear-gradient(to bottom, #bddbfa 5%, #80b5ea 100%);
    border: 1px solid #84bbf3;
    color: #ffffff;
    text-shadow: 0 1px 0 #528ecc;
}

10. Now Check in Browser window similar to the window as shown.

-------------------------------------------------------------------------------------------------

11. Adding some data in component to display while we navigate:

 Open subject.component.ts file and add/modify as follows the class SubjectComponent

 subjects = [
    { id: 12, name: 'Networks' },
    { id: 13, name: 'C' },
    { id: 14, name: 'C++' },
    { id: 15, name: 'Angular' },
    { id: 16, name: 'React' },
    { id: 17, name: 'Java' },
    { id: 18, name: 'Python' },
    { id: 19, name: 'HTML' },
    { id: 20, name: 'CSS' }
 
   ];

12. Add the following contents to student.component.html file:
<div *ngFor="let s of subjects">
    <div style="color: #0000ff">
        {{s.id}}:  {{s.name}}:
    </div>
</div>


13. Open subject.component.ts file and add/modify as follows the class SubjectComponent and save

 students = [
    { id: 102, name: 'Dr. Nice' },
    { id: 103, name: 'Bombasto' },
    { id: 104, name: 'Celeritas' },
    { id: 105, name: 'Magneta' },
    { id: 106, name: 'RubberMan' },
    { id: 107, name: 'Dynama' },
    { id: 108, name: 'Dr. IQ' },
    { id: 109, name: 'Magma' },
    { id: 200, name: 'Tornado' }
  ];

12. Add the following contents to subject.component.html file and save:
<div *ngFor="let s of students">
    <div style="color: #0000ff">
        {{s.id}}:  {{s.name}}:
    </div>
</div>


13. Check these output in browser window by typing ng server in terminal http://localhost:4200 in browser

Happy Learning Angular !!!💁💁


Exercise 

1. Modify file app.component.css with the following contents 

.button {
    box-shadow: inset 0 1px 0 0 #ffffff;
    background: #ffffff linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);
    border-radius: 6px;
    border: 1px solid #dcdcdc;
    display: inline-block;
    cursor: pointer;
    color: #666666;
    font-family: Arial, sans-serif;
    font-size: 15px;
    font-weight: bold;
    padding: 6px 24px;
    text-decoration: none;
    text-shadow: 0 1px 0 #ffffff;
    outline: 0;
}

.activebutton {
    box-shadow: inset 0 1px 0 0 #dcecfb;
    background: #bddbfa linear-gradient(to bottom, #bddbfa 5%, #80b5ea 100%);
    border: 1px solid #84bbf3;
    color: #ffffff;
    text-shadow: 0 1px 0 #528ecc;
}


2. Modify the first <a> tag in app.component.html as follows:

<a class="button"
     routerLink="/student"
     routerLinkActive="activebutton"
     ariaCurrentWhenActive="page">Student List</a> |
 

Check your browser output.

No comments:

Post a Comment

Angular 18 Navigation for iMMSS

  🚀 Setting Up Angular Routing - The Fun Way! 😆 Hey there, future Angular ninjas! 🥷 If you’re new to Angular and struggling with routing...