To call or navigate to a component from another component in Angular, you typically use Angular's Router service for component routing. Here's how you can achieve this.

Define Routes in the Router Module

First, you need to set up your routes in your AppRoutingModule (or any routing module you've defined). Define the paths and the corresponding components.

TypeScript
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ComponentA } from './component-a/component-a.component';
import { ComponentB } from './component-b/component-b.component';

const routes: Routes = [
  { path: 'component-a', component: ComponentA },
  { path: 'component-b', component: ComponentB },
  // Add more routes as needed
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

You can navigate to another component using the RouterLink directive in your template (HTML) of the first component.

HTML / XML
<!-- component-a.component.html -->
<a [routerLink]="['/component-b']">Go to Component B</a>

You can also navigate programmatically using the Angular Router in your component's TypeScript file.

TypeScript
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-component-a',
  templateUrl: './component-a.component.html',
  styleUrls: ['./component-a.component.css']
})
export class ComponentA {

  constructor(private router: Router) { }

  goToComponentB() {
    this.router.navigate(['/component-b']);
  }
}

In HTML template

HTML / XML
<!-- component-a.component.html -->
<button (click)="goToComponentB()">Go to Component B</button>

Outlet to Render Routed Components

Ensure you have a <router-outlet></router-outlet> in your main HTML template (e.g., app.component.html) where the routed components will be displayed.

HTML / XML
<!-- app.component.html -->
<router-outlet></router-outlet>

Lazy Loading (Optional)

If you want to load a module lazily, define your route like this.

TypeScript
const routes: Routes = [
  {
    path: 'component-b',
    loadChildren: () => 
      import('./component-b/component-b.module')
        .then(m => m.ComponentBModule)
  }
];

Summary

  • RouterLink: For navigation within the template.
  • Router.navigate: For programmatic navigation within the component's TypeScript file.
  • Router Outlet: Acts as a placeholder in the template where routed components are displayed.

This setup allows you to call or navigate between components effectively in Angular.