I have a global js variable defined below (@Url is an ASP.Net MVC html helper it will get converted to a string value):
<script>
var rootVar = '@Url.Action("Index","Home",new { Area = ""}, null)';
System.import('app').catch(function(err){ console.error(err); });
</script>
How do I access rootVar in an angular2 component? I used to use the window service in angular 1.5, is there an analogous way of doing that in angular2?
Specifically, I want to use that rootVar variable to help generate the templateUrl in this component:
import { Component, Inject} from '@angular/core';
@Component({
selector: 'home-comp',
templateUrl: '../Home/Root'
})
export class HomeComponent {
constructor( ) { }
}
We always need to declare global variable file for our angular 10 application because we can set some global variable there like site title, api url etc so you can easily access any where in our application easily. So, in this example, we will create GlobalConstants file for adding global variables in our application.
To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.
Within your component you could reference window to access the global variables like so:
rootVar = window["rootVar"];
or
let rootVar = window["rootVar"];
You need to update the file that bootstraps your application to export a function:
import {bootstrap} from '...';
import {provide} from '...';
import {AppComponent} from '...';
export function main(rootVar) {
bootstrap(AppComponent, [
provide('rootVar', { useValue: rootVar })
]);
}
Now you can provide the variable from the index.html
file this way:
<script>
var rootVar = '@Url.Action("Index","Home",new { Area = ""}, null)';
System.import('app/main').then((module) => {
module.main(rootVar);
});
</script>
Then you can inject the rootVar
into components and services this way:
import { Component, Inject} from '@angular/core';
@Component({
selector: 'home-comp',
templateUrl: '../Home/Root'
})
export class HomeComponent {
constructor(@Inject('rootVar') rootVar:string ) { }
}
In the component file, outside component class definition, declare rootVar, and it will become available in the component constructor:
declare var rootVar: any;
then
@Component(...)
export class MyComponent {
private a: any;
constructor() {
this.a = rootVar;
}
}
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