I have a simple component in Angular 4 that is as follows:
HTML
<div [style.clip-path]="shape" [style.background-color]="color"</div>
and the only thing I have added to the .ts file is:
color = 'green';
shape = 'polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%)';
There is some styling that makes the div
400px by 400px.
When I serve this code I see a green box, meaning the style binding does work for at least background-color
. However the box is still a square and not the pentagon that I defined. clip-path
seems to not be set properly.
Weirder still I tested this with Angular 2 and it functions as expected.
Did something change from Angular 2 -> Angular 4 that would deny binding to particular style attributes?
It's not working because it's being sanitized.
You need to use DomSanitizer
. From the docs:
Calling any of the
bypassSecurityTrust...
APIs disables Angular's built-in sanitization for the value passed in. Carefully check and audit all values and code paths going into this call. Make sure any user data is appropriately escaped for this security context. For more detail, see the Security Guide.
So, inject the DomSanitizer
and use bypassSecurityTrustStyle
.
private _polygon = 'polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%)';
public get polygon() {
return this.sanitizer.bypassSecurityTrustStyle(this._polygon);
}
constructor(private sanitizer: DomSanitizer) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With