angular 5 - bind full style expression

706 Views Asked by At

i wont to bind a full style expression for an html element.

for example: expression like this in home.ts:

divStyle:string = "top:50%;bottom:50%;color:green;";

and in home.html i was try these ways to bind the style to the element:

<div class="preloader" [attr.style]="divStyle">

or

<div class="preloader" [style]="divStyle">

or

<div class="preloader" [ngStyle]="divStyle">

But it did not work.

any body know if it's possible to do it?

3

There are 3 best solutions below

0
On BEST ANSWER

Due to security constraints; you will need to first sanitize the style string by using the DOM sanitizer:

Component:

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  divStyle: string = 'background-color: red; font-weight: 600;';

  constructor(private sanitizer: DomSanitizer){}

  sanitize(style: string) {
    return this.sanitizer.bypassSecurityTrustStyle(style);
  }
}

Template:

<div [style]="sanitize(divStyle)">
  Content
</div>

Working sample: https://stackblitz.com/edit/angular-pkjd2q


Ideally, you should use a different approach such as the NgStyle directive which expects a style object, not a string. You would need to do the following:

Component:

divStyle: string = { top: "50%", bottom: "50%", color: "green" };

Template:

<div [ngStyle]="divStyle"></div>
1
On

Maybe try with something with this form:

<div class="preloader" 
    [ngStyle]="{'top': '50%',
                'bottom': '50%',
                'color': 'green'}">
0
On

as @Gorka Hernandez mentioned, it might be more elegant with pipes, like:

shared.pipe.ts

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {

  constructor(protected sanitizer: DomSanitizer) {}

  public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
            case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
            case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
            case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
            case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
            case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
            default: throw new Error(`Invalid safe type specified: ${type}`);
        }
  }

}

custom.pipe.ts

@Pipe({
  name: 'severityColor'
})
export class SeverityColorPipe extends SafePipe implements PipeTransform {

  constructor(protected sanitizer: DomSanitizer){
    super(sanitizer)
  }

  transform(severity: number): SafeStyle {
    switch (severity) {
      case 9:
      case 10:
        return super.transform('background-color: rgba(255, 165, 0, .2)', 'style');
    
      default:
        break;
    }
  }

}

usage:

custom.html

<div *ngFor="let severity of severities">
    <div [style]="severity | severityColor"></div>
</div>