Issue
How can I add separate CSS for one page in Angular?
The two standard solutions to this problem, I've both discounted:
Using
::ng-deep
orViewEncapsulation.None
. CSS added in this way won't be removed when navigating away from the component, and therefore we can't use it.Adding a class to the
body
viangOnInit/ngOnDestroy
. The CSS I want to add can't be attached to thebody
, so this isn't suitable.
This is the CSS I need, as per How to remove the URL from the printing page?:
@media print{
@page{
margin:0;
}
body{
margin:30px;
}
}
I've added a Stackblitz, which explains the problem clearly.
Perhaps the question would be better summarized as "How to add global CSS, but remove it when we leave the page?".
Solution
Solved!
We print the <style>
block directly into the component's HTML, and therefore when the component gets removed, our <style>
block gets removed too. (Normally this wouldn't work, but thanks to DomSanitizer.bypassSecurityTrustHtml
, Angular won't break our code when running optimizations.)
Here's a StackBlitz.
First, create a new component to handle the work:
component.ts: (This is all we need. We don't need an HTML or style.css file.)
// Usage Instructions:
// Inside your local component, place this HTML
// <app-local-css [style]="'body{background:green !important;}'"></app-local-css>
// OR
// <app-local-css [scriptURL]="'/path/to/file.css'"></app-local-css>
@Component({
selector: "app-local-css",
template: '<span style="display:none" [innerHTML]="this.safeString"></span>'
})
export class LocalCSSComponent implements OnInit {
constructor(protected sanitizer: DomSanitizer) {}
@Input() scriptURL?: string;
@Input() style?: string;
safeString: SafeHtml;
ngOnInit() {
if (this.scriptURL) {
let string = '<link rel="stylesheet" type="text/css" href="' + this.scriptURL + '">';
this.safeString = this.sanitizer.bypassSecurityTrustHtml(string);
} else if (this.style) {
let string = '<style type="text/css">' + this.style + "</style>";
this.safeString = this.sanitizer.bypassSecurityTrustHtml(string);
}
}
}
And then use it like this:
mySample.component.html:
<app-local-css [style]="'body{background:green !important;}'"></app-local-css>
// OR
<app-local-css [scriptURL]="'/path/to/file.css'"></app-local-css>
Answered By - Eliezer Berlin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.