欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 【angular19】入门基础教程(四):默认的css隔离作用域

【angular19】入门基础教程(四):默认的css隔离作用域

2025/4/30 21:07:05 来源:https://blog.csdn.net/qq_27702739/article/details/147602954  浏览:    关键词:【angular19】入门基础教程(四):默认的css隔离作用域

众所周知,在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效果,成为了私有的组件级别的类型。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词