All! I've this component where when I click on the href it is supposed to set a variable as Root Scope if it was Angular 1 like this:
selector: 'my-component' template : ` <div (click)="addTag(1, 'abc')">` constructor() { this.addTag = function(id, desc){ myGlobalVar = { a: id, b: desc}; };
Then in my parent component, the page itself (in fact) I should be doing something like:
<my-component></my-component> <p>My Component is returning me {{ ?????? }}
What is the best approach to do such a thing?
Angular 2 is component based. Components combine concepts that we are already familiar with from AngularJS. The Angular 2 Component combines the AngularJS Directive, Controller, and Scope.
All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.
What is alternative of rootScope in Angular? In similar way, you can use use the sharedService inside any component & fetch the returing output and used inside your view. That's it. I found this solution as a good alternative of rootScope.
The controllers and $scope in Angular 1 have been replaced with “Components” in Angular 2. Hence we can say that it is a component-based framework, which uses zone.
To implement global variable, you could implement a shared service. You will be able to save data it and all components could have access to them.
For this, simply implement a service and set its provider when boostrapping your application:
bootstrap(AppComponent, [ MySharedService ]);
Be careful not to define it again within the providers
attribute of components where you want to use it.
Sample
The service:
export class MySharedService { data: any; dataChange: Observable<any>; constructor() { this.dataChange = new Observable((observer:Observer) { this.dataChangeObserver = observer; }); } setData(data:any) { this.data = data; this.dataChangeObserver.next(this.data); } }
Use it into a component:
@Component({ (...) }) export class MyComponent { constructor(private service:MySharedService) { } setData() { this.service.setData({ attr: 'some value' }); } }
If you want to notify components that the data were updated you can leverage observable fields into the shared service:
@Component({ (...) }) export class MyComponent { constructor(private service:MySharedService) { this.service.dataChange.subscribe((data) => { this.data = data; }); } }
See this question for more details:
This page on the angular.io website could also interest you:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With