angular 5 - 绑定完整样式表达式

angular 5 - bind full style expression

我不会为 html 元素绑定完整样式表达式。

例如:home.ts中的表达式:

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

home.html 中,我尝试了这些方法将样式绑定到元素:

<div class="preloader" [attr.style]="divStyle">

<div class="preloader" [style]="divStyle">

<div class="preloader" [ngStyle]="divStyle">

但是没有用。

有人知道是否可以这样做吗?

也许尝试使用这种形式的东西:

<div class="preloader" 
    [ngStyle]="{'top': '50%',
                'bottom': '50%',
                'color': 'green'}">

由于安全限制;您需要先使用 DOM 消毒剂 消毒 样式字符串:

分量:

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 directive,它需要一个样式对象,而不是一个字符串。您需要执行以下操作:

分量:

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

模板:

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

正如@Gorka Hernandez 提到的,使用管道可能更优雅,例如:

shared.pipe.ts

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {

  constructor(protected sanitizer: DomSanitizer) {}

  public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
            case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
            case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
            case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
            case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
            case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
            default: throw new Error(`Invalid safe type specified: ${type}`);
        }
  }

}

custom.pipe.ts

@Pipe({
  name: 'severityColor'
})
export class SeverityColorPipe extends SafePipe implements PipeTransform {

  constructor(protected sanitizer: DomSanitizer){
    super(sanitizer)
  }

  transform(severity: number): SafeStyle {
    switch (severity) {
      case 9:
      case 10:
        return super.transform('background-color: rgba(255, 165, 0, .2)', 'style');
    
      default:
        break;
    }
  }

}

用法:

custom.html

<div *ngFor="let severity of severities">
    <div [style]="severity | severityColor"></div>
</div>