Angular5给组件本身的标签添加样式class的方法

在Angular 5给组件本身的标签添加样式有两种方法

方式一:使用@Component的host属性

rush:js;"> @Component({ selector : 'myComponent',host : { '[style.color]' : "'red'",'[style.background-color]' : 'backgroundColor' } }) class MyComponent { backgroundColor: string; constructor() { this.backgroundColor = 'blue'; } }

在host配置里添加属性,等同于标签上绑定属性用法一样。

设置style:

  1. '[style.color]': "'red'":注意red值双引号里还有一个单引号。
  2. '[style.background-color]':'backgroundColor':这里是引用了组件里的变量backgroudColor。

这种方式的好处是可以在样式上使用组件的变量。

设置class:

rush:js;"> @Component({ selector : 'myComponent',host : { '[class.myclass]' : 'showMyClass' } }) class MyComponent { showMyClass = false; constructor() { }

toggleMyClass() {
this.showMyClass = !this.showMyClass;
}
}

方式二:在样式里使用:host选择器

rush:js;"> @Component({ selector : 'myComponent',styles : [` :host { color: red; background-color: blue; } `] }) class MyComponent {}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...