您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Angular4中显示CSS样式的示例代码

2025/5/12 16:49:53发布9次查看
本文主要给大家介绍了关于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 样式。
相关推荐:
详解一个完整的angular4 formtext 组件的实现方法
angular4表单响应功能示例分析
angular4中项目的准备和环境搭建操作
以上就是angular4中显示css样式的示例代码的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product