Search code examples
angularangular8ng-styleangular2-ngcontent

How to bind data in ngStyle using Angular


I'm trying to bind data using Angular 8 but failing miserably. One of the methods I tried is as below:

<div class="speed" style="background-image: url('http://example.com/assets/images/meter.png')" [ngStyle]="{'--p':result.percentage}"></div>

and the output:

<div _ngcontent-kyh-c1="" class="speed" style="background-image: url('http://example.com/assets/images/meter.png');" ng-reflect-ng-style="[object Object]"></div>

I want the output to be:

<div _ngcontent-kyh-c1="" class="speed" style="background-image: url('http://example.com/assets/images/meter.png');--p:24;"></div>

FYI, {{result.percentage}} gives and an output 24.

Please ignore _ngcontent-kyh-c1="" which is generated by Angular 8.


Solution

  • Add this into your ts component. It will add style to your component

    import { DomSanitizer } from '@angular/platform-browser';
    import { ChangeDetectionStrategy, Component, HostBinding } from '@angular/core';
    
    @Component({
        selector: 'my-component',
        templateUrl: './my-component.html',
        styleUrls: ['./my-component.scss'],
        changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class MyComponent  {
    
        @HostBinding('attr.style')
        public get valueAsStyle(): any {
           return this.sanitizer.bypassSecurityTrustStyle(`--p: ${this.result.percentage}`);
        }
    
        constructor(private sanitizer: DomSanitizer) {}
    }
    

    Now in html you will have ..... So hostBinding is great way to modify your host components

    Now I am able to use variable in nested html just using color: var(--p) will change my text to red. This is what I assume you want to achieve