简体   繁体   中英

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'>

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'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM