Dynamically Updating CSS in Angular 2

Dynamically updating css in Angular 2

Try this

 <div class="home-component" 
[style.width.px]="width"
[style.height.px]="height">Some stuff in this div</div>

[Updated]:
To set in % use

[style.height.%]="height">Some stuff in this div</div>

Angular 2 - How to dynamically change an entire CSS stylesheet based on URL queryparams

After a lot of digging around, finally found the solution I was looking for.
And it was so straight forward, hope this helps others that might be needing to do the same thing..

Get the css path from query params and then Inject the Document into a TS file...
append the link to the head of the document.

I did this in a Router Guard using canActivate.
I got the query param from the routerstatesnpshot like so:

Inject the DOCUMENT( don't forget the import) in the constructor

http://server.com/xxx&broker=1&client=2&css=http://cssServer.com/my_dynamic_stylesheet.css

   import { DOCUMENT } from '@angular/common';

@Inject(DOCUMENT) private document: Document

this.setDynamicStyle(state.root.queryParamMap.get('css'));

setDynamicStyle(cssURL: string) {
const head = this.document.getElementsByTagName('head')[0];
const style = this.document.createElement('link');
style.id = 'css-styling';
style.rel = 'stylesheet';
style.href = `${cssURL}`;
head.appendChild(style);
}

Thanks to:
https://juristr.com/blog/2019/08/dynamically-load-css-angular-cli/

Angular2 dynamic change CSS property

Just use standard CSS variables:

Your global css (eg: styles.css)

body {
--my-var: #000
}

In your component's css or whatever it is:

span {
color: var(--my-var)
}

Then you can change the value of the variable directly with TS/JS by setting inline style to html element:

document.querySelector("body").style.cssText = "--my-var: #000";

Otherwise you can use jQuery for it:

$("body").css("--my-var", "#fff");

How to dynamically change CSS in :host in angular 2?

Here is a working example.

Use the following HostBinding:

@HostBinding('style.overflow-y') overflowY = 'scroll';

This would give the following component:

@Component({
selector: 'my-app',
template: `
<div>
<button (click)="addStyle()">Add Style</button>
<h2>Hello</h2>
</div>`, styles: [
`
:host {
overflow-x: hidden;
height: 50px;
width: 200px;
display: block;
}
`,
],
})
export class App {
name: string;

@HostBinding('style.overflow-y')
overflowY = 'scroll';

constructor() {
}

addStyle() {
this.overflowY = 'hidden';
}
}

Generate dynamic css based on variables angular

Direct approach available in angular is using ngstyle as follows

<div [ngStyle]="{'color': style.colorVal ? style.colorVal : '#000', 'font-size' : style.fontSize ? style.fontSize : '16px' }"></div>

After going through different methods and approached to add dynamic css to all pages on angular app I ended up with following solutions.

Requirement : generate dynamic css based on values returned from and API to change design and styling.

Solution :

  1. create a new component and create a service to load dynamic css variables from API.
  2. Add style tag in template file and use variable values for properties.
  3. Load this template on all pages or on main template.
  4. On app build style will be moved to head tag.

Code sample

import { CssService} from './Css.service';

@Component({
selector: 'DynamicCss',
templateUrl: './DynamicCss.component.html',
styleUrls: ['./DynamicCss.component.scss']
})
export class ServiceProviderComponent implements OnInit {
cssVariables: any;
constructor(private cssService:CssService){
/* call the service/api to get the css variable values in cssVariables */

}
}

Now apply css using jquery or javascript to append css with help of function like following

appendCss(customData)
{
let text = '.custom-form-1 {
background-image: url("`+customData.background_image+`");
}';
$(document).ready(function(){
$("style").append(text);
});
}

and call this function after loading custom data from service or other variable like I did it ngOnInit

ngOnInit(){
this.appendCss(this.customizeFormData);
}

Its using jquery but can be done with javascript/typescript as well if you dont want to use jquery in your angular app

Other useful resource https://github.com/angular/angular/issues/9343#issuecomment-312035896



Related Topics



Leave a reply



Submit