How to pass data between components in Angular

In Angular, you can pass data between components using a variety of methods. Here are three common methods:

  1. Input and Output Decorators:You can use the @Input() and @Output() decorators to pass data between parent and child components. The @Input() decorator allows a parent component to pass data to a child component, while the @Output() decorator allows a child component to emit an event that a parent component can subscribe to.

    Here is an example:

    In the parent component:

    <app-child [message]="parentMessage" (messageEvent)="receiveMessage($event)"></app-child>
    

     

    In the child component:

    @Input() message: string;
    @Output() messageEvent = new EventEmitter<string>();
    
    sendMessage() {
      this.messageEvent.emit(this.message);
    }
    

     

    In this example, the parent component is passing the parentMessage string to the child component using the message input property. The child component is then emitting an event with the messageEvent output property when a button is clicked, and passing the message back to the parent component using the $event parameter.

    Service:

    You can create a service that holds the data to be shared between components. The service can be injected into each component that needs access to the data. When the service is updated, the updated data will be available to all components that are using the service.

    Here is an example:

    // service
    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable()
    export class DataService {
      private messageSource = new BehaviorSubject<string>("default message");
      currentMessage = this.messageSource.asObservable();
    
      changeMessage(message: string) {
        this.messageSource.next(message);
      }
    }
    
    // parent component
    export class ParentComponent {
      constructor(private dataService: DataService) { }
    
      changeMessage() {
        this.dataService.changeMessage("Hello from parent");
      }
    }
    
    // child component
    export class ChildComponent {
      message: string;
    
      constructor(private dataService: DataService) { }
    
      ngOnInit() {
        this.dataService.currentMessage.subscribe(message => this.message = message)
      }
    }
    

     

    In this example, the DataService is used to store a message that is shared between the parent and child components. The ParentComponent can call the changeMessage() method to update the message in the service. The ChildComponent can subscribe to the currentMessage observable to get the current message from the service.

    Route Parameters:

    You can use route parameters to pass data between components that are linked by a route. The data can be included in the route URL and accessed by the receiving component using the ActivatedRoute service.

    Here is an example:

    // app-routing.module.ts
    const routes: Routes = [
      { path: 'product/:id', component: ProductComponent }
    ];
    
    // parent component
    export class ParentComponent {
      constructor(private router: Router) { }
    
      goToProduct(id: number) {
        this.router.navigate(['/product', id]);
      }
    }
    
    // child component
    export class ProductComponent {
      id: number;
    
      constructor(private route: ActivatedRoute) { }
    
      ngOnInit() {
        this.id = this.route.snapshot.params['id'];
      }
    }
    

     

  2. In this example, the ParentComponent can navigate to the ProductComponent and pass an id parameter in the URL. The ProductComponent can access the id parameter using the `ActivatedRoute

Leave a Reply

Your email address will not be published. Required fields are marked *