SoFunction
Updated on 2025-04-08

Methods of passing values ​​and communication between different components in angular

This article mainly introduces how angular transmits values ​​and communicates in different components. It is mainly divided into parent-child components and non-parent-child components.

Parameters and communication methods between parent and child components

Use event communication (EventEmitter, @Output):

Scenario: Communication can be carried out between parent and child components, generally using the child components to pass messages to parent components;

step:

  1. The child component creates an event EventEmitter object and exposes it using @output;
  2. The parent component listens to the method out of the child component @output and then handles the event.

Code:

 // child component  @Component({
   selector: 'app-child',
   template: '',
   styles: [``]
  })
  export class AppChildComponent implements OnInit {
   @Output() onVoted: EventEmitter<any> = new EventEmitter();
   ngOnInit(): void {
    (1);
   }
  }
  // parent component  @Component({
   selector: 'app-parent',
   template: `
    <app-child (onVoted)="onListen($event)"></app-child>
   `,
   styles: [``]
  })
  export class AppParentComponent implements OnInit {
   ngOnInit(): void {
    throw new Error('Method not implemented.');
   }
   onListen(data: any): void {
    ('TAG' + '---------->>>' + data);
   }
  }

Use @ViewChild and @ViewChildren:

Scenario: Generally used to pass information to child components, or the parent component calls child components;

step:

  1. Use child components in the parent component;
  2. Use @ViewChild in the parent component to obtain the child component object.
  3. The parent component uses the child component object to manipulate the child component; (pass information or call methods).

Code:

// Subcomponents@Component({
 selector: 'app-child',
 template: '',
 styles: [``]
})
export class AppChildComponent2 implements OnInit {
  data = 1;
  ngOnInit(): void {
 }
 getData(): void {
  ('TAG' + '---------->>>' + 111);
 }
}
// Parent component@Component({
 selector: 'app-parent2',
 template: `
  <app-child></app-child>
 `,
 styles: [``]
})
export class AppParentComponent2 implements OnInit {
 @ViewChild(AppChildComponent2) child: AppChildComponent2;
 ngOnInit(): void {
  (); // Parent component obtains child component method  ('TAG'+'---------->>>'+);// Parent component obtains child component properties }
}

Non-parent-child component parameter transfer and communication methods

By routing parameters

Scenario: One component can be routed to another component, such as: list and edit

step:

  1. Component A jumps to component B through routerLink or page
  2. Component B accepts these parameters

This method is only suitable for parameter passing, and the parameters between components will not change once received

Code

Transmission method

routerLink

<a routerLink=["/exampledetail",id]></a>

routerLink=["/exampledetail",{queryParams:object}]

routerLink=["/exampledetail",{queryParams:'id':'1','name':'yxman'}];

(['/exampledetail',id]);
(['/exampledetail'],{queryParams:{'name':'yxman'}});

('/exampledetail/id');
('/exampledetail',{queryParams:{'name':'yxman'}});

After the transmission of the parasite, the two ways of receiving the parasite are as follows:

snapshot

import { ActivateRoute } from '@angular/router';
public data: any;
export class ExampledetailComponent implements OnInit { 
  constructor( public route: ActivateRoute ) { };
  ngOnInit(){
     = ['id'];
  };
}

queryParams

import { ActivateRoute } from '@angular/router';
export class ExampledetailComponent implements OnInit { 
  public data: any;
  constructor( public activeRoute:ActivateRoute ) { };
  ngOnInit(){
    (params => {
     = params['name'];
  });
};

Use service to communicate, that is, two components inject a service at the same time

Scenario: The two components that need communication are not parent-child components or adjacent components; of course, they can also be any component.

step:

  1. Create a new service, and component A and component B inject the service at the same time;
  2. Component A obtains data from the service, or wants to transmit data from the service
  3. Component B obtains data from a service, or wants the service to transmit data.

Code:

  // Component A  @Component({
   selector: 'app-a',
   template: '',
   styles: [``]
  })
  export class AppComponentA implements OnInit {
   constructor(private message: MessageService) {
   }
   ngOnInit(): void {
    // Component A sends message 3    (3);
    const b = (); // Component A receives messages;   }
  }
  // Component B  @Component({
   selector: 'app-b',
   template: `
    &lt;app-a&gt;&lt;/app-a&gt;
   `,
   styles: [``]
  })
  export class AppComponentB implements OnInit {
   constructor(private message: MessageService) {
   }
   ngOnInit(): void {
    // Component B gets the message    const a = ();
    (5); // Component B sends a message   }
  }

Message service module

Scenario: This involves a project, which requires the implementation of possible communication between all components, or a component needs to communicate with several components, and cannot be transmitted through routing.

Design method:

  1. Use RxJs to define a service module MessageService, and all information is registered with the service;
  2. Where a message is needed, call the method of the service;
  3. Use the place where information is needed, call the method of receiving information, obtain a Subscription object, and then listen to the information;
  4. Of course, when every component Destory is required
();

Code:

  // Message Technical Technical Service  @Injectable()
  export class MessageService {
   private subject = new Subject&lt;any&gt;();
   /**
    * Information transmission is carried out in the content module, similar to broadcasting
    * @param type The type of information sent
    * 1-Your information
    * 2-Your information
    * 3-Your information
    * 4-Your information
    * 5-Your information
    */
   sendMessage(type: number) {
    ('TAG' + '----------&gt;&gt;&gt;' + type);
    ({type: type});
   }
   /**
    * Clean up messages
    */
   clearMessage() {
    ();
   }
   /**
    * Get message
    * @returns {Observable<any>} Return message listening
    */
   getMessage(): Observable&lt;any&gt; {
    return ();
   }
  }
  // Where to use this service, you need to register the MessageService service;  constructor(private message: MessageService) {
  }
  // Where the message is accepted;  public subscription: Subscription;
  ngAfterViewInit(): void {
     = ().subscribe(msg =&gt; {
     // According to msg, handle your business logic.    })
   }

   // When the component life cycle ends, remember to log out, otherwise it will get stuck;   ngOnDestroy(): void {
    ();
   }

   // Call the service method and send information;   send():void {
    (‘I've sent a message,You accept it'); // Send message   }

The MessageService here is equivalent to using a broadcast mechanism to pass information between all components; whether it is numbers, strings, or objects, they can be passed, and the propagation speed here is also very fast.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.