Issue
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.
Solution
Another way is using a service. You have to use the service as a "store" of your data values:
- Create a service:
ng g s MyServiceName --skip-Tests
Once it is created, check that has been decorated as providedIn root:
@Injectable({
providedIn: 'root',
})
export class MyServiceNameService {
....
- In your service, declare all data you want the components share (have in commun), and create methods setters/getters for this data. e.g:
private _myVariable: string;
get myVariable(){
return _myVariable;
}
set myVariable(newValue: string){
this._myVariable = newValue;
}
constructor(){
_myVariable = "exampletest";
}
- Inject the service in the constructor of your components (in parent and in child):
...
import { MyServiceNameService } from '../../services/my-service-name.service';
...
constructor(
private myServiceNameService : MyServiceNameService ) {
}
...
- Used directly the variables in the service through methods in the service to modify the varaibles values or get its values.
e.g: in components:
let myVariable:string;
....
getNewValue(){
myVariable = this.myServiceNameService.myVariable;
}
setNewValue ( newValue: string) {
this.myServiceNameService.myVariable(newValue);
}
Answered By - Juan Vicente Berzosa Tejero
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.