Angular改变组件中样式(两种方法)

项目中遇到修改组件样式的情况,搜了半天资料基本只有vue和react的方法,什么/deep/,v-deep统统不起效,崩溃!

所以这里总结一下Angular的方法。

angular中想引入组件并修改组件内样式,有两种方法。

方法1:::ng-deep

注意,此方法在文档中写已弃用,但仍能生效(博主写下此博客的版本:Angular16)。

在这里插入图片描述
文档:文档

::ng-deep要注意以下几点:

  • 对应css文件不是全局的,即在ts中没有encapsulation: ViewEncapsulation.None
  • 注意优先级

对于第二点,如果想要对.noc-switch-group--true这个类修改样式,且原本的样式为:

.noc-switch-group .noc-switch-group--true {
    
    
    background-color: #53b38f;
}

那么以下代码不会生效:因为都是一个类选择器。

::ng-deep .noc-switch-group--true {
    
    
    background-color: #0b66e5;
  }

在这里插入图片描述
解决方法:使自己的优先级变高,如多加一个类选择器:.switchBlue是我们在调用组件的父级添加的类。

::ng-deep .switchBlue .noc-switch-group--true {
    
    
  background-color: #0b66e5;
}

这样也行(有什么区别?):

.switchBlue ::ng-deep .noc-switch-group--true {
    
    
  background-color: #0b66e5;
}

在这里插入图片描述

在这里插入图片描述

成功!

方法2:将css修改为全局,覆盖组件内的样式

在对应ts文件:

import {
    
     Component, ViewEncapsulation } from '@angular/core'; //引入ViewEncapsulation

@Component({
    
    
  selector: 'task-list',
  templateUrl: './task-list.component.html',
  styleUrls: ['./task-list.component.scss'],
  encapsulation: ViewEncapsulation.None, //将此css设置为全局
})

对应的样式就不会因为某个类不存在于代码中(只存在组件中)而不出现。

css可以直接写:

noc-switch .noc-switch-group--true {
    
    
  background-color: #0b66e5;
}

显然代码生效了。

在这里插入图片描述
这里也有优先级的问题,在使用组件的父级添加类,在css使用类选择器,提升优先级。

.switchBlue .noc-switch-group--true {
    
    
  background-color: #0b66e5;
}

成功!

猜你喜欢

转载自blog.csdn.net/karshey/article/details/134056907