6

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:

enter image description here

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!

someblue
  • 485
  • 1
  • 6
  • 8
  • [style.box-shadow] is not work too. Does Angular style binding just support limited css type? I can't find related document from Angular official website or Google. – someblue Dec 28 '17 at 13:19

1 Answers1

11

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:

  1. https://stackoverflow.com/a/38663363/1009922
  2. https://stackoverflow.com/a/37267875/1009922
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146