Search code examples
javascriptangularproperty-binding

What is wrong with this property binding in Angular4 while using it on style property?


In Angular4, property binding on the view (.html) picks up the value from the logic file (.ts)

This works well in the code:

<img [src]="sourceValue"> 

This too works well in the code:

<button [disabled]="isDisabled"> 

Why does this not work?

<p [style]="paragraphStyle"> This is a paragraph.</p>

abc.component.ts

isDisabled:boolean = true; 
sourceValue:string = "./assets/hermione.jpg"; 
paragraphStyle:string = "background:red; color:yellow";

I know the usage of ngStyles and ngClass, I simply want to ask why property binding is not working in the above case. It is finally --- just a simple "Inline CSS Styling" if value is taken from .ts file and added to the html snippet in front of 'style' property in paragraph.


Solution

  • It's because of security Measures:

    @Angular docs
    Angular defines the following security contexts:

    • HTML is used when interpreting a value as HTML, for example, when
      binding to innerHtml.
    • Style is used when binding CSS into the style property.
    • URL is used for URL properties, such as <a href>.

    • Resource URL is a URL that will be loaded and executed as code, for example, in <script src>.

    The Fix is to sanitize values beforehand using bypassSecurityTrustStyle()- Bypass security and trust the given value to be safe style value (CSS).

    @Angular docs

    WARNING: calling this method with untrusted user data exposes your application to XSS security risks!

    Component:

    import { Component, SecurityContext } from '@angular/core';
    import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular';
      paragraphStyle;
    constructor(private _sanitizer: DomSanitizer){ 
    
      this.paragraphStyle=this._sanitizer.bypassSecurityTrustStyle("background-color:red");
    }
    

    HTML

    <p [style]="paragraphStyle"> This is a paragraph.</p>
    

    NOTE:

    For style property name use dash-case. For example, font-weight ,background-color

    Live Demo