This is somewhat an open discussion but I'm really curious about passing data dynamically from one component to another.
I know it can be done using @Input() decorator. But it has its disadvantages like you can't use the back button on your browser. Because if you do, then you will do back an entire page. It won't work in the Parent-Child method because we're using ng-If to hide the child directives on a page and It won't update the content dynamically unless you reload that page. And when you reload that page, you lose the current state of the UI.
If the data is static then there's absolutely no problem but when it's dynamic and you try to pass the data, it shows as undefined.
I would appreciate any pointers on how would I be able to achieve that.
Another way is using a service. You have to use the service as a "store" of your data values:
ng g s MyServiceName --skip-Tests
Once it is created, check that has been decorated as providedIn root:
@Injectable({
providedIn: 'root',
})
export class MyServiceNameService {
....
private _myVariable: string;
get myVariable(){
return _myVariable;
}
set myVariable(newValue: string){
this._myVariable = newValue;
}
constructor(){
_myVariable = "exampletest";
}
...
import { MyServiceNameService } from '../../services/my-service-name.service';
...
constructor(
private myServiceNameService : MyServiceNameService ) {
}
...
e.g: in components:
let myVariable:string;
....
getNewValue(){
myVariable = this.myServiceNameService.myVariable;
}
setNewValue ( newValue: string) {
this.myServiceNameService.myVariable(newValue);
}
There could be multiple ways here:
You can create angular service (use @Injectable() annotation to create service). Angular service follows singleton design pattern and can be shared among multiple pages of your application. Wherever you need, just inject that service and you can access all properties/methods.
Link how to create angular service -
You can use redux concept and create a store having data & then that data could be accessible across all pages. NgRx is the best library with Angular to create store and access data wherever needed. NgRx link -
You can use RxJs library to share data between peer components.
RxJs link -
Use a shared service and create an observable inside the service, then inject this service to the components need to access this shared data and create a subscription on each component. When ever the data in the observable changes the subscribed components will get notified.