I am working on an Angular 14 project where I need to comply with a strict Content Security Policy (CSP) that includes the directive “style-src ‘self'”. This means I cannot have any inline-styles in my application.
How can I completely remove inline styles to ensure that I can use style src ‘self’ in my CSP? Is there any additional configuration or workaround needed to prevent Angular from inlining styles?
I cannot use ngCspNonce here as it is not supported in Angular version 14.
I tried setting the ‘inlineCritical’ option to ‘false’ in the angular.json file under the build configurations, expecting it to remove the inline styles.
"build": {
"configurations": {
"optimization": {
"scripts": true,
"styles": {
"minify": true,
"inlineCritical": false
}
},
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
}
}
Console errors
First thing to know is that style-src directive includes style-src-elem and style-src-attr. This is important because setting inline-critical to false is only going help with style-src-elem since it stops Angular from creating a style element with inline css to speed up the style loading.
Good luck dealing with style-src-attr: You’re going to have to find an alternative to every usage the NgStyle directive, binding to a style attribute, and static style attribute. The solution will likely involve the NgClass directive. Oh, and hope that no third-party component is using inline styles.
The easiest thing would be to add a new directive for style-src-attr:
style-src-attr 'self' 'unsafe-inline'