您好,欢迎访问一九零五行业门户网

Angular 4中显示CSS样式

这次给大家带来angular 4中显示css样式,angular 4中显示css样式的注意事项有哪些,下面就是实战案例,一起来看一下。
在开始本文的正文之前,我们先来看一下angular2中将带标签的文本输出在页面上的相关内容,为了系统性的防范xss问题,angular默认把所有值都当做不可信任的。 当值从模板中以属性(property)、dom元素属性(attribte)、css类绑定或插值表达式等途径插入到dom中的时候, angular将对这些值进行无害化处理(sanitize),对不可信的值进行编码。
h3>binding innerhtml</h3> <p>bound value:</p> <p class="e2e-inner-html-interpolated">{{htmlsnippet}}</p> <p>result of binding to innerhtml:</p> <p class="e2e-inner-html-bound" [innerhtml]="htmlsnippet"></p>
[innerhtml]=htmlsnippet
这个属性可以识别 html标签 但不识别标签中的属性值
发现问题
大家都知道angular 中有 innerhtml 属性来设置要显示的内容,但是如果内容包含 css 样式,无法显示样式的效果。
比如:
public content: string = <p style='font-size:30px'>hello angular</p>; <p [innerhtml]="content"></p>
只会显示 hello world ,字体不会是 30px,也就是 css 样式没有效果。
解决方案
自定义一个 pipe 来对内容做转换。看下面代码。
写一个 htmlpipe 类
import {pipe, pipetransform} from @angular/core; import {domsanitizer} from @angular/platform-browser; @pipe({  name: html }) export class htmlpipe implements pipetransform{  constructor (private sanitizer: domsanitizer) {  }  transform(style) {  return this.sanitizer.bypasssecuritytrusthtml(style);  } }
在需要的模块里面引入管道 htmlpipe
@ngmodule({  declarations: [  htmlpipe  ] })
在 innerhtml 中增加管道名字
<p [innerhtml]="content | html"></p>
这样就可以显示 content 的 css 样式。
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
以上就是angular 4中显示css样式的详细内容。
其它类似信息

推荐信息