Reputation: 7057
Is there a way to add stylesheet url or <style></style>
dynamically in Angular2 ?
For example, if my variable is isModalOpened
is true
, I would like to add some CSS to few elements outside my root component. Like the body
or html
.
It's possible to do it with the DOM or jQuery but I would like to do this with Angular 2.
Possible ?
Thanks
Upvotes: 6
Views: 3845
Reputation: 2601
You can create a <style>
tag dynamically like this:
ngOnInit() {
const css = 'a {color: pink;}';
const head = document.getElementsByTagName('head')[0];
const style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(css));
head.appendChild(style);
}
Upvotes: 5
Reputation: 9331
I am not sure you can do it to body or html, but you can do it to root component.
BehaviorSubject
) isModalOpened
is changed Update : Setting background color from an inner component .
app.component.css
.red{
background: red;
}
.white{
background: white;
}
.green{
background: green;
}
app.component.html
<div [ngClass]="backgroundColor" ></div>
app.component.ts
constructor(private statusService: StatusService) {
this.subscription = this.statusService.getColor()
.subscribe(color => { this.backgroundColor = color; });
}
status.service.ts
private color = new Subject<any>();
public setColor(newColor){
this.color.next(newColor);
}
public getColor(){
return this.color.asObservable();
}
child.component.ts
export class ChildComponent {
constructor(private statusService: StatusService) {}
setColor(color:string){
this.statusService.setColor(color);
}
}
So whenever we call setColor and pass a color variable such as 'red', 'green' or 'white' the background of root component changes accordingly.
Upvotes: 1
Reputation: 1632
Put all your html code in a custom directive - let's call it ngstyle...
Add your ngstyle to your page using the directive tags, in our case:
<ngstyle><ngstyle>
but let's also append the logic to your directive using ng-if so you can toggle it on or off...
<ngstyle ng-if="!isModalOpened"><ngstyle>
Now if your 'isModalOpened' is set to a scope in your controller like this:
$scope.isModalOpened = false; //or true, depends on what you need
...you can toggle it true or false many different ways which should toggle your directive on and off.
Upvotes: 0