Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have components Save button trigger action on different component in Angular?

I have an angular component using an NGPrime datatable.... When a user selects a row they get a popup component that lets them edit the data.... after they edit the data they can click 'save' button. How can I send that save button click action to the component with the datatable so I can trigger a refresh of the data?

like image 901
Joe Starnes Avatar asked Jul 28 '26 04:07

Joe Starnes


1 Answers

You have several ways for this.

If they are unrelated components then

Generic Service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class ShareService  {   
  constructor() { } 
  private paramSource = new BehaviorSubject("");
  sharedData = this.paramSource.asObservable();
  setParam(param:string) { this.paramSource.next(param)}    
}

put in providers in appmodule

providers:[ShareService ]

put in constructors in components

constructor(private shareService: ShareService  ){}

from first component send like

this.shareService.setParam('Sending param');

from second component receive like

 this.shareService.sharedData.subscribe(data=> { console.log(data); })

Routing Method

you can put parameter in router and send it. You can make router as parametric like your routing.ts

{ path: 'component/:param', component: RelatedComponent },

then in component you want to get it call like import ActiveRoute in constructor

constructor(private route: ActivatedRoute){}

and get like

this.route.snapshot.paramMap.get('param')

or if you dont want to show param in route you can send as state like below code

this.router.navigate(['your_component_url'], {state: { param: 'data you send' } });

to read state in constructor this.router.getCurrentNavigation().extras.state.param;

Storage Method

you can set to localStorage or sessionStorage then take from storage from another component.

localStorage.setItem("param","parameter")

localStorage.getItem("param")

If they are parent child components then you can do above too and also much prefable to use

@Input method

<your_child_component param="{{ parameter}}"></your_child_component>

in child component getlike

@Input param;
like image 51
mr. pc_coder Avatar answered Jul 30 '26 19:07

mr. pc_coder