angular - 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?
解决方案
由于安全限制;您需要首先使用 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>
推荐阅读
- ios - Swift:视图控制器触摸事件中的自定义 UIButton 类未触发?
- php - 使用服务器调用外部 API
- python - Python 版本 >= 3.4 不提供有效的 PIP 实用程序。后面好像不能加
- python - 仅从磁铁 uri 下载 .torrent 文件。不确定我实际下载的是什么
- python - 从另一个模块导入模块时没有名为“....”的模块
- rest - 作为多部分文件发布到给定的端点
- ocaml - 了解Ocaml的结构
- python - 用于 Azure 活动日志的 python 脚本
- javascript - 带有 ASP.Net Web 表单的 Bing Map AutoSuggest API
- spring-boot - 在资源服务器上解码 Spring Boot 2.1 OAuth2 编码的 JWT