Inject CSS variable names that come form the server (Angular 12) - css

I'm trying to find the best solution to inject css variables into angular application (currently using Angular 12).
This is the code I'm using:
private injectStyles(data: any) {
const styles = this.document.createElement('STYLE') as HTMLStyleElement;
styles.id = 'dynamic-css';
this.test = `:root {
--main-bg-color: black;
}`;
styles.innerHTML = this.test;
this.renderer.appendChild(this.document.head, styles);
}
This code is being executed on app.component.ts file and this works quite well, i can use this css variable throughout the whole application.
What I'm trying to achieve now is to extend the this.test Object with data that comes from the server and apply these custom css values that were set on my Visual settings module before.
Css variables must not have "" quotes.
"--button-color": "#a86c6c" (this is what I get from the server) and I would like to inject this property without quotes on the this.test Object and I can't do that. Any ideas?
Any help is highly appreciated,
Thanks.

Object.keys is your friend
let dataString = '';
Object.keys(data).forEach(key => {
dataString += `${key}: ${data[key]};`
});
this.test = `:root {
--main-bg-color: black;
${dataString}
}`;
If needed, you may need to add quote to the value like this
`dataString += `${key}: "${data[key]};"`

Related

Typescript - create type of all available css properties

I'm using React and Styled Components and I have a function that accepts a string of a css attribute. I want to type it to validate that the string is a valid css attribute (color, background-color, etc...)
function doSomething(cssPropertyName: SomeType) {
}
doSomething('border-color'); // No error
doSomething('non-existing-css-property'); // Should give an error
How can I achieve this?
Thanks!
With: https://github.com/frenic/csstype I think you can simply use:
function doSomething(prop: keyof CSSProperties) {
}
doSomething('borderColor'); // No error
doSomething('non-existing-css-property'); // Should give an error

Dynamically switch global CSS for Angular8 app (client branding)

I want to dynamically switch Angulars global CSS files based on which client is connecting. This will be used for client-branding purposes, including fonts, colors, photos, headers, footers, button-styles, etc.
Each client has provided us with a CSS file, which we need to integrate into our app. We have hundreds of clients.
Current solution is to try and override the CSS of individual components at load. This is bad because it adds a lot of boilerplate:
Html:
<link id="theme" rel="stylesheet" href="./assets/stylesheets/{{cclientCode}}.css">
ts:
ngOnInit() {
this.service.clientCode.subscribe(clientCode => this.clientCode = clientCode);
}
My workaround isn't working because the link html is called before the {{}} has a chance to load in the value.
I'm also not motivated to fix my workaround because its just that -a workaround. Instead, I want to implement something that works globally, without any per-component boilerplate.
What I want is the ability to dynamically switch the global Angular style for each client. So something like:
"styles": [
"src/assets/stylesheets/angular_style.css",
"src/assets/stylesheets/client_style.css"
]
Where client_style.css is served differently to each client.
I've found a solution that I think is workable. It definitely has issues though, so if anyone has their own answer, please still share!
First, I added a clientCode String field to SessionDataService, a global service I use to move component-agnostic data around my app:
export class SessionDataService {
clientCode: BehaviorSubject<String>;
constructor(){
this.clientCode = new BehaviorSubject('client_default');
}
setClientCode(value: String) {
this.clientCode.next(value);
}
}
Then, inside app.component.ts, I added a BehaviorSubject listener to bring in the value of clientCode dynamically:
public clientCode: String;
constructor(private service : SessionDataService) {
this.service.clientCode.subscribe(clientCode => this.clientCode = clientCode);
}
Next, I added a wrapper around my entire app.component.html:
<div [ngClass]="clientCode">
--> ALL app components go here (including <router-outlet>)
</div>
So at this point, I've created a system that dynamically adds client-code CSS classes to my components, including all children :)
Finally, I just have to write CSS rules:
.ClientOne p {
color: red;
}
.ClientOne .btn {
background-color: red;
}
.ClientTwo.dashboard {
height: 15%;
}
I hope this helps somebody! Essentially the "trick" here is to add a ngClass that wraps the entire app, and then justify all client-specific CSS rules with their client code.

Unload/remove dynamically loaded css files

After loading a css file like this:
const themes = ['dark-theme.css', 'light-theme.css'];
async function loadcss(file) {
return await import(file);
}
loadcss(themes[0]).then(console.log)
The console output is an empty object for me and a new annonymous < style> tag sits in the < head> of my index.html. So far so good, but what if I (in this example) want to change the theme to light-theme.css. That would merge both themes as dark-theme.css is already loaded.
Is there a way to remove the < style> tag from the DOM?
To furthermore specify my question, the provided example shows an abstracted behaviour and I am only interested in removing the dynamically loaded css from the DOM.
I don't know vue.js but here is simple example in React hope it helps somehow :) perhaps some ideas at least :)
class TodoApp extends React.Component {
static themes = {
dark: 'dark-theme.css',
light: 'light-theme.css',
};
render() {
return ReactDOM.createPortal(
(<link rel="stylesheet" href={TodoApp.themes.dark} type="text/css"></link>),
document.head
);
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
http://jsfiddle.net/3y4hw2ox/
Thanks to OZZIE, I questioned my methodology and found, that importing the css files, like my question shows (through ES6 import, or require.context(...)), is not usefull, as we can't identify it, we dont get access to the <style> element, leaving us with no entry to the DOM and no way to manipulate it.
Instead we will link the css files manually in the <head>, as we know their name and path.
const themes = ['dark-theme.css', 'light-theme.css'];
const head = document.body.parentElement.firstElementChild;
const link = document.createElement('link');
link.setAttribute('href', process.env.BASE_URL + themes[0]);
link.setAttribute('id', themes[0]); // set id so we can remove it later
head.appendChild(link);

Is it possible to apply dynamic style as string in Angular?

I have a <span> that I want to apply dynamic style to.
Style is stored in a css-like string variable and can be arbitrary e.g.
myStyle = 'color: white; font-weight: bold;'
or
myStyle = 'background-color: red;'
I expected it to work like
<span style="{{myStyle}}">
but it didn't.
I tried different options but none seem to work for me for different reasons:
I can't put styles in a .css file and use class names because style is coming from server in the form of aforementioned string
Using [style.color] etc. doesn't suit me because I don't know what the style can be
Using [ngStyle] doesn't suit me because it expects object like {'color': 'red', 'font-weight': 'bold'} and I only have string
The reason I have a style stored in a string is because I need to apply it in HTML generated on the server where I simply pass that string to a placeholder variable in a velocity template.
I am almost confident that it can't be done the way I want but probably I am overlooking some solution.
All you need is DomSanitizer and bypassSecurityTrustStyle
Component side :
import { DomSanitizer } from '#angular/platform-browser';
constructor(private doms : DomSanitizer) {}
newStyle = 'background-color:red';
safeCss(style) {
return this.doms.bypassSecurityTrustStyle(style);
}
Template side :
<p [style]="safeCss(this.newStyle)">
Start editing to see some magic happen :)
</p>
WORKING DEMO
Angular provides the DomSanitizer service which can convert strings into style objects. I think this is exactly your case.
constructor(private sanitizer: DomSanitizer) {
}
sanitizeStyle() {
return this.sanitizer.bypassSecurityTrustStyle('background-color: red');
}
<span [style]="sanitizeStyle()">
I think I will go the way of converting the incoming css string into a style object and then applying it to <span> using [ngStyle]

Using Css to Clear TextBox Text/value

I was wondering, if it was possible to clear a text box with a css code rather than using javascript ?
This isn't possible with CSS, only with JS:
Event handler function:
addEvent(document.getElementById('IDHERE'), "focus",
function() {
clearText('IDHERE');
});
Event listener function:
//addEvent listener
function addEvent(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
} else {
if (obj.attachEvent) {
obj["e" + type + fn] = fn;
obj[type + fn] = function() {
obj["e" + type + fn](window.event);
};
obj.attachEvent("on" + type, obj[type + fn]);
}
}
}
ClearText function:
//Clear on focus function
function clearText(id) {
document.getElementById(id).value = "";
}
This is pure JS, no libraries needed here, very fast and x-browser compatible :)
You cannot use CSS to manipulate the DOM. In other words: this is not possible.
With CSS one cannot change a document, only the look and behaviour of the document but that's it.
This is impossible. CSS is for presentation only, HTML is for the information and structure and javascript is for DOM manipulation. You will have to use Javascript or one of its libraries to do this :)
can be done, but just in a visual way, it wont actually go, but wont be shown too
there can be many tricks, one can be to set the text color same as the background of your text box, disable selection.
but if you want it to be completely gone you need to use javascript

Resources