Merijndk
Merijndk

Reputation: 1693

acces javascript var in template angular 2

I have a angular app with a few settings defined in my index.php:

 <script>
    Setting = { imagepath : "some/path/", setting2: 1}
 </script>

 <myapp>

 </myapp>

Now I want to acces this image path variable in one of my templates so that the img path can always be changed without trouble. How can I pass the settings object to my angular template so I can use

<img [src]="settings.imagePath+'/myimage.png'>

Upvotes: 1

Views: 42

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657118

In template bindings the scope is limited to the components class instance.

If you want to access it from template bindings anyway you need to add a method or getter to your component class that returns that value.

This should do what you want:

 <script>
    window.Setting = { imagepath : "some/path/", setting2: 1}
 </script>
export class MyComponent {
  get settings() {
    return window.Settings;
  }
}
<img [src]="settings.imagePath+'/myimage.png'>

Upvotes: 2

Related Questions