angularng-style

angular 5 - bind full style expression


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?


Solution

  • 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>