Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 'filter' style binding not work

Tags:

css

angular

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!

like image 997
someblue Avatar asked Dec 28 '17 13:12

someblue


1 Answers

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
like image 173
ConnorsFan Avatar answered Oct 07 '22 18:10

ConnorsFan