Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 465
levi Avatar asked Feb 28 '26 19:02

levi


2 Answers

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>
like image 93
Gorka Hernandez Avatar answered Mar 02 '26 09:03

Gorka Hernandez


Maybe try with something with this form:

<div class="preloader" 
    [ngStyle]="{'top': '50%',
                'bottom': '50%',
                'color': 'green'}">
like image 31
Marc Avatar answered Mar 02 '26 08:03

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!