首页 > 解决方案 > 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?

标签: angularng-style

解决方案


由于安全限制;您需要首先使用 DOM sanitizer 来清理样式字符串

零件:

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);
  }
}

模板:

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

工作样本: https ://stackblitz.com/edit/angular-pkjd2q


理想情况下,您应该使用不同的方法,例如NgStyle 指令,它需要一个样式对象,而不是字符串。您需要执行以下操作:

零件:

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

模板:

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

推荐阅读