I was doing the research if it is possible to use the SCSS variable value in HTML or TS in Angular.
For example
I have a variable called $mdBreakpoint: 992px; inside _variable.scss file
In html I have a condition
[ngClass]="{'col-sm-3': innerWidth >= 992}"
992 is the same value as the $mdBreakpoint
My question is it possible to refer $mdBreakpointin HTML condition.
I am using Angular 8
It's not directly supported by Angular, html or sass. You can't access scss variables in a html template without writing some logic.
See this answer if you want more information on how to do it: access SASS values ($colors from variables.scss) in Typescript (Angular2 ionic2)
You can create a variable which holds value of mdBreakpoint and then use it HTML template:
TypeScript:
mdBreakpoint = 992;
HTML:
[ngClass]="{'col-sm-3': innerWidth >= mdBreakpoint }"
UPDATE:
It seems that there is no way to access SASS now, but if you want to have a something like global variable, then you can create your variable in environment.ts file and use in any component:
export const environment = {
production: false,
MD_BREAKPOINT: 992
};
and in your component:
export class YourComponent {
title = 'myapp works!';
mdBreakpoint = environment.MD_BREAKPOINT;
}
Related
In my vue project I have a default image that should show up in places around the app when an image is missing or hasn't been uploaded yet. I have various class files and component calls that want to use the same image.
What is the best way to create a global variable that I can access from anywhere? I can't put it in the store because my class files (I'm using vuex-orm) are loaded before the store is declared. I would prefer not to put it in the window because I want to have a single word variable that I can call (defaultImg as opposed to window.my_project.globals.defaultImg). I could put it in .env but I want this to be checked into the repository and the same across environments so that doesn't seem right either.
What is the best way to provide a simple global string to all files in my vue project?
Are you using Vue 2 or 3? TL;DR best approach is to create a component.
Quick Fix
You could take the approach described in the documentation for creating plugins:
https://vuejs.org/guide/reusability/plugins.html#introduction
If you didn't want to go down the convoluted route of creating a separate plugin file just to store a single string you could probably just do something like this in your entry file where you initialize the app:
Vue 3:
app.config.globalProperties.$defaultImg = '/path/to/image.png'
Vue 2:
Vue.prototype.$defaultImg = '/path/to/image.png'
And use this in your templates like
<img :src="$defaultImage">
Best Solution
However, I think the best and the most 'Vue' way would be to create an image component which displays a given image, or the default image if src is nullish:
Vue 2 & 3
<template>
<img :src="srcOrDefault">
<template>
Vue 3 Composition API:
<script>
const defaultImg = '/path/to/image.png'
const props = defineProps({
src: String
});
const srcOrDefault = computed(() => {
return props.src || defaultImg
})
</script>
Vue 2 & Vue 3 Options API:
<script>
const defaultImg = '/path/to/image.png'
export default {
props: {
src: String
},
computed: {
srcOrDefault() {
return this.src || defaultImg
}
}
}
</script>
I was wondering if it's possible to use the content of a ts variable and use it in js file ?
I'm feeling trapped now I realize that I don't know how can I achieve it.
Please send me any suggestion easy to implement if possible.
My ts file with the printedOption that I want to use in my js file.
The content of this variable is the value of my select input.
validateLuggages() {
this.printedOption = this.selectedOption;
this.http.get(`/routes/luggages`)
.subscribe((data) => {
this.parsedForLuggages = data;
})
return this.printedOption;
}
Now, How can I create the instance and use this variable in my JS file ?
To use any typescript variable inside javascript code you may firstly export the variable in typescript file which you want to use in the js file.
Then, you can simply use the import statement and import the variable from the correct path.
You can check the example below and refer the link for better clarity. LINK
// Add to tsconfig.json:
{
"compilerOptions": {
...
"allowJs": true
...
}
}
import MyModule from './../pages/MyModule';
I've got a component where I'm trying to define a function that reads through the following js file and checks if a certain string value is contained in it. How can I do it? It's path is '../../../assets/beacons.js' (from my component) and it's named beacons.js
const allBeacons = {
"RIPE": [
"84.205.64.0/24",
"84.205.65.0/24",
"84.205.67.0/24",
"84.205.68.0/24",
"84.205.69.0/24",
"84.205.70.0/24",
"84.205.71.0/24",
"84.205.74.0/24",
"84.205.75.0/24",
"84.205.76.0/24",
"84.205.77.0/24",
"84.205.78.0/24",
"84.205.79.0/24",
"84.205.73.0/24",
"84.205.82.0/24",
"93.175.149.0/24",
"93.175.151.0/24",
"93.175.153.0/24"].map(i => i.toLowerCase()),
"rfd.rg.net": [
"45.132.188.0/24",
"45.132.189.0/24",
"45.132.190.0/24",
"45.132.191.0/24",
"147.28.32.0/24",
"147.28.33.0/24",
"147.28.34.0/24",
"147.28.35.0/24",
"147.28.36.0/24",
"147.28.37.0/24",
"147.28.38.0/24",
"147.28.39.0/24",
"147.28.40.0/24",
"147.28.41.0/24",
"147.28.42.0/24",
"147.28.43.0/24",
"147.28.44.0/24",
"147.28.45.0/24",
"147.28.46.0/24",
"147.28.47.0/24"].map(i => i.toLowerCase())
}
You need to include the js file in the bundle by telling angular about it:
Open angular.json, and add the path to the "scripts" array:
"scripts": ["src/assets/beacons.js"]
In the top of your component file (before class declaration) declare the variable as global so typescript won't complain about it (the name must match to the one in the js file):
type Beacons = {/* Define type if you want */} | any
declare const allBeacons: Beacons
Now you can use it as a global variable in your app:
ngOnInit() {
console.log(allBeacons)
}
I'm trying to include "parameters.js" file into my angular 4 project.
You can see below my "parameter.js" file content :
window.myKey = "http://webserviceUrl/"
I want to include this file in my project and get "myKey" value in a typescript file before loading web service datas.
My "parameters.js" file as a specific structure and do not be changed (no json :'( ).
Is anyone as loading js into typescript with angular 4 ? How can i do that ?
Thanks for your help.
Include the script in index.html
<script src="/assets/parameters.js" />
And declare the variable in the component where you need to access it
declare let myKey: string;
According to David explainations, i have added my parameters script in my angular conf ".angular-cli.json" like this :
"scripts": [
"../directory/parameters.js"
],
I can read the value in typescript with the code :
declare let myKey: string;
Thank you David for you great response ! :)
You can Import js locally to ts file like this : import '../../../scripts/custom.js';
then declare method name in custom.js that you want to use like this 👍
declare var fAlert;
(declarations statements are usually put just after the import statements)
then in a place like ngOnInit directly use this method
fAlert();
I am working on a project that requires using a js plugin. Now that we're using vue and we have a component to handle the plugin based logic, I need to import the js plugin file within the vue component in order to initialize the plugin.
Previously, this was handled within the markup as follows:
<script src="//api.myplugincom/widget/mykey.js
"></script>
This is what I tried, but I am getting a compile time error:
MyComponent.vue
import Vue from 'vue';
import * from '//api.myplugincom/widget/mykey.js';
export default {
data: {
My question is, what is the proper way to import this javascript file so I can use it within my vue component?
...
Include an external JavaScript file
Try including your (external) JavaScript into the mounted hook of your Vue component.
<script>
export default {
mounted() {
const plugin = document.createElement("script");
plugin.setAttribute(
"src",
"//api.myplugincom/widget/mykey.js"
);
plugin.async = true;
document.head.appendChild(plugin);
}
};
</script>
Reference: How to include a tag on a Vue component
Import a local JavaScript file
In the case that you would like to import a local JavaScript in your Vue component, you can import it this way:
MyComponent.vue
<script>
import * as mykey from '../assets/js/mykey.js'
export default {
data() {
return {
message: `Hello ${mykey.MY_CONST}!` // Hello Vue.js!
}
}
}
</script>
Suppose your project structure looks like:
src
- assets
- js
- mykey.js
- components
MyComponent.vue
And you can export variables or functions in mykey.js:
export let myVariable = {};
export const MY_CONST = 'Vue.js';
export function myFoo(a, b) {
return a + b;
}
Note: checked with Vue.js version 2.6.10
try to download this script
import * from '{path}/mykey.js'.
or import script
<script src="//api.myplugincom/widget/mykey.js"></script>
in <head>, use global variable in your component.
For scripts you bring in the browser way (i.e., with tags), they generally make some variable available globally.
For these, you don't have to import anything. They'll just be available.
If you are using something like Webstorm (or any of the related JetBrains IDEs), you can add /* global globalValueHere */ to let it know that "hey, this isn't defined in my file, but it exists." It isn't required, but it'll make the "undefined" squiggly lines go away.
For example:
/* global Vue */
is what I use when I am pulling Vue down from a CDN (instead of using it directly).
Beyond that, you just use it as you normally would.
I wanted to embed a script on my component and tried everything mentioned above, but the script contains document.write. Then I found a short article on Medium about using postscribe which was an easy fix and resolved the matter.
npm i postscribe --save
Then I was able to go from there. I disabled the useless escape from eslint and used #gist as the template's single root element id:
import postscribe from 'postscribe';
export default {
name: "MyTemplate",
mounted: function() {
postscribe(
"#gist",
/* eslint-disable-next-line */
`<script src='...'><\/script>`
);
},
The article is here for reference:
https://medium.com/#gaute.meek/how-to-add-a-script-tag-in-a-vue-component-34f57b2fe9bd
For anyone including an external JS file and having trouble accessing the jQuery prototype method(s) inside of the loaded script.
Sample projects I saw in vanilla JS, React and Angular were simply using:
$("#someId").somePlugin(options)
or
window.$("#someId").somePlugin(options)
But when I try either of those in my VueJS component I receive:
Error: _webpack_provided_window_dot$(...).somePluginis not a function
I examined the window object after the resources had loaded I was able to find the jQuery prototype method in the window.self read-only property that returns the window itself:
window.self.$("#someId").somePlugin(options)
Many examples show how to load the external JS file in VueJS but not actually using the jQuery prototype methods within the component.