为了账号安全,请及时绑定邮箱和手机立即绑定

模板之样式绑定

属性绑定中的样式绑定

模板之数据绑定 的属性绑定中,我们没有提及样式绑定,因为样式绑定的内容较多,而且在工作中也很常用,所以在此进行单独整理。

通过 class 实现样式绑定

绑定单个 class

绑定单个 class,只需要使用前缀 class 后跟 className 即可。

例子:

// html
<p [class.textStyle]="styleShow">Everything is fine</p>

// css
.textStyle{
  font-size: 30px;
  color: brown;
}

// ts
styleShow = true;

*styleShow 为 true 时添加 class,反之删除 class。

绑定多个 class

绑定多个 class 时,会使用正常的属性绑定 [class] 后跟变量或表达式的形式。
变量或表达式可以取以下值:

1、字符串

例子:

// html
<p [class]="styleList">Everything is fine</p>

// css
.textStyle{
  font-size: 30px;
  color: brown;
}
.textBg{
  background-color: cadetblue;
}

// ts
styleList = 'textStyle textBg';

2、数组

例子:

// html
<p [class]="styleList">Everything is fine</p>

// css
.textStyle{
  font-size: 30px;
  color: brown;
}
.textBg{
  background-color: cadetblue;
}

// ts
styleList = ['textStyle','textBg'];

3、className 并以布尔值判断是否添加的对象

例子:

// html
<p [class]="styleList">Everything is fine</p>

// css
.textStyle{
  font-size: 30px;
  color: brown;
}
.textBg{
  background-color: cadetblue;
}

// ts
styleList = {textStyle:true, textBg:false};

通过 style 实现样式绑定

绑定单个 style

绑定单个 style,只需要使用前缀 style 后跟样式名即可。

例子:

// html
<p [style.font-size]="textStyle">Everything is fine</p>

// ts
size = '30px';

绑定多个 style

同样的,绑定多个 style 时,也会使用正常的属性绑定 [style] 后跟变量或表达式的形式。
变量或表达式可以取以下值:

1、字符串

例子:

// html
<p [style]="textStyle">Everything is fine</p>

// ts
textStyle = 'font-size:30px; color: brown';

2、对象

例子:

// html
<p [style]="textStyle">Everything is fine</p>

// ts
textStyle = {'font-size':'30px', 'color': 'brown'};

end

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
1.4万
获赞与收藏
860

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消