众所周知,在vue和react框架中,我们css都是全局作用域的,如果不显示声明为私有的组件级别作用域,会影响到全局的布局样式。
所以在vue中,需要配置scoped这样的属性来限制css的作用范围,在react中相对来说要复杂点,css module或者第三方的styled-component解决方案是比较常见的
效果展示
代码实现
- 父组件
import {Component,signal,computed,effect,inject,Injector,untracked,
} from '@angular/core';
import { ChildComp } from '../ChildComp1/index';@Component({selector: 'UserProfile',templateUrl: './index.html',styleUrls: ['./index.css'],imports: [ChildComp],
})
export class UserProfile {}
<main class="main-box"><h2>{{title}}</h2><div><p>{{userInfo.name}}</p><p>{{userInfo.age}}</p><p>{{userInfo.sex}}</p><p>{{userInfo.address.city}}</p><p>{{userInfo.address.street}}</p><button (click)="handleChangeName()">改变姓名</button><p>我银行账户的存款:{{money()}}</p><p>需要换银行的贷款:{{payload()}}</p><button (click)="handleChangeAge()">改变存款</button><button (click)="reset()">重置</button><!-- <button (click)="handleChangePayload()">降低贷款</button> --><child-comp /></div>
</main>
- 子组件
<div class="main-box"><h2>{{title}}</h2>
</div>
import { Component } from '@angular/core';
@Component({selector: 'child-comp',templateUrl: './index.html',styleUrls: ['./index.css'],
})
export class ChildComp {title = 'child-demo';
}
如何禁用这种默认的组件级别样式
先看效果
在ng中也考虑到了这个问题,也给我们三种配置样式作用域
- ViewEncapsulation.Emulated 默认的效果
- ViewEncapsulation.ShadowDom 此模式严格保证只有该组件的样式才应用于组件模板中的元素。
- ViewEncapsulation.None 与组件关联的任何样式都表现为全局样式。
这样就实现了样式的全局作用域
原理分析
可以看到ng在组件编译后,自动给组件的类名加上了指纹,类似于css的module和vue中的scoped效果,成为了私有的组件级别的类型。