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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风清云淡_A

觉得有帮助的话可以给点鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值