首页 文章

Angular:为什么color CSS属性设置向下传播到嵌套组件?

提问于
浏览
1

以下是Angular guide关于样式范围和继承的说法:

@Component元数据中指定的样式仅适用于该组件的模板 . 嵌套在模板中的任何组件或投影到组件中的任何内容都不会继承它们

如果需要在嵌套树下传播样式,建议用户明确

使用/ deep / shadow-penetcing后代组合子将样式向下强制通过子组件树到所有子组件视图中 .

// For example, this should make all h3 elements down the nesting-tree italic: 

    :host /deep/ h3 {
      font-style: italic;
    }

我们来看看这个示例设置:

app.component.ts

@Component({
    selector: 'app-root',
    template: `
        <div class="my-container">
            <app-hello></app-hello>                // <-- a nested component
            This is local txt in app component
        </div>
    `,
    styles: ['.my-container { color: red; }']
})
export class AppComponent {}

hello.component.ts

@Component({
  selector: 'app-hello',
  template: `<h1>Hello Component!</h1>`
})
export class HelloComponent {}

Expected: app-component 中的文本为红色, hello-component 中的文本为黑色

Observed: 两个文本都是红色的 . Why ?

演示Stackblitz

2 回答

  • 5

    在您的示例中,它只是基本的CSS继承:您说div的颜色是红色,并且您没有为该div的子元素明确指定任何其他颜色 . 所以你的孩子组件当然会有红色文字;这只是CSS的正常行为 .

    现在假设您向父元素添加 h1 并添加规则以将其颜色更改为绿色 .

    template: `
      <div class="my-container">
      <h1>hellllooooo</h1>
        <app-hello></app-hello>
        This is local txt in app component
      </div>`,
     styles: ['.my-container { color: red; } h1 {color: green}']
    

    在这种情况下,来自父级的h1将为绿色,但此规则不会泄漏到子级的h1,它仍然是继承的(在您的示例中为红色) .

    这正是你引用的那个意思

    @Component元数据中指定的样式仅适用于该组件的模板 . 嵌套在模板中的任何组件或投影到组件中的任何内容都不会继承它们

    Stackblitz demo

    Edit :创建了另一个演示,演示 /deep

    parent.ts

    @Component({
      selector: 'app-root',
      template: `
            <app-hello></app-hello>
          <div class=container2>Text inside container2 div in parent - green</div>
      `,
      styles: ['.container2 {color: green}']
    })
    

    child

    @Component({
      selector: 'app-hello',
      template: `
      <div class=container2>Text inside container2 div in child </div>`,
    
    })
    

    因为,内容是子元素将是 black ,而不是绿色 . 父样式不会泄漏 . 现在,您将父样式修改为

    styles: ['/deep/ .container2 {color: green}']
    

    然后,子div中的颜色将为绿色 .

    2nd stackblitz demo

  • 0

    意味着样式传播以这种方式工作 .

    如果在父组件中定义了一个类 .my-class {...} ,则窗口可以传播给子组件:

    • 通过CSS继承(继承颜色属性)

    • 如果父项中的样式定义明确标记为'visible',例如通过 :host /deep/ .my-class { ... }

    Takeaway :shadow DOM不会停止CSS继承(p.1),它会停止类命名传播,可以在(p.2)中启用

    演示Stackblitz

相关问题