This content originally appeared on Level Up Coding - Medium and was authored by Dennis
I am creating an angular template whereby I can create forms from a data file automatically, such as a json or yaml. For displaying on the monitor screen, the fields should have different sizes depending on what is the subject of the field.
Like in the example above, the building and the unit field will take up less screen space compared to other fields like street field. As the form is generated on demand, the fields are not known in advanced and my css isn’t so clever to know which fields need less space than others. So I’d want to have the field length in my data file. Not in pixels, but just in percentage of the screen width. To do that, I need to pass data from my Angular to my css, which is a bit tricky, but I’ve found a way.
CSS Variables are just like normal variables that you can define in your css file or the style property of your html tags. The syntax to define the variable is --[NAME]:[VALUE]. So, to define a css variable named size with a value of 50% in my style property, I can do something like this:
<div style="--size:50%">hello</div>
Since this is in the html, I can use angular data binding to set the value — --size:{{rect}}.
Below is an example where I have an array of percentage width defined in the property named rects.
export class AppComponent {
name = 'Angular ' + VERSION.major;
rects = ['100%', '50%', '30%'];
}
Then in my html template, I define the css variable named size, with the values from the iteration of my rects property.
<div *ngFor="let rect of rects" style="--size:{{ rect }}">
{{ rect }}
</div>
And lastly, I can get the value of my css variable with the syntax --var([NAME]).
In my example, I set the value of the width css attribute of my div with the variable, to produce divs of different lengths based on the value in my angular data.
div {
background-color: cornflowerblue;
display: block;
width: var(--size);
margin: 10px;
}
A working example is available on my Stackblitz.
Level Up Coding
Thanks for being a part of our community! Before you go:
- 👏 Clap for the story and follow the author 👉
- 📰 View more content in the Level Up Coding publication
- 🔔 Follow us: Twitter | LinkedIn | Newsletter
🚀👉 Placing developers like you at top startups and tech companies
How to pass data from Angular to CSS was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Dennis
Dennis | Sciencx (2022-09-26T02:59:22+00:00) How to pass data from Angular to CSS. Retrieved from https://www.scien.cx/2022/09/26/how-to-pass-data-from-angular-to-css/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.