There is an example
@Component({
selector: 'my-app',
template: `
<div>
<h2 style="background-color:green">
No Filter
</h2>
</div>
<div style="filter:brightness(0.5)">
<h2 style="background-color:green">
Filter with style.
</h2>
</div>
<div [style.filter]="'brightness(' + val + ')'">
<h2 style="background-color:green">
Filter with style binding.
</h2>
</div>
<p>filter binding express value: {{'brightness(' + val + ')'}}</p>
`,
})
export class App {
val = 0.5;
}
https://plnkr.co/edit/gD9xkX5aWrdNDyD6fnIh?p=preview
got the rendered result:
Seem like style binding [style.filter] not work. Anyone know the reason or give another way to control filter brightness style by component member value?
Thanks for any answer!
When we apply the filter style like this:
<div [style.filter]="'brightness(' + val + ')'">
the following message appears in the console:
WARNING: sanitizing unsafe style value brightness(0.5)
The style expression brightness(0.5)
is considered unsafe by Angular. We can mark it as safe by calling DomSanitizer.bypassSecurityTrustStyle
in a method of the component class or with the help of a custom pipe defined as:
import { Pipe } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";
@Pipe({name: 'safe'})
export class SafePipe {
constructor(private sanitizer: DomSanitizer){
}
transform(style) {
return this.sanitizer.bypassSecurityTrustStyle(style);
}
}
which can be applied like this in the template:
<div [style.filter]="'brightness(' + val + ')' | safe">
An alternative, which does not involve sanitization problems, is to use the ngStyle
directive:
<div [ngStyle]="{'filter': 'brightness(' + val + ')'}">
Both techniques are shown in this stackblitz.
The problem of unsafe style expressions has been discussed in other posts:
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