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

zag*_*ggi 1 angular

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

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

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

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

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

    :host /deep/ h3 {
      font-style: italic;
    }
Run Code Online (Sandbox Code Playgroud)

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

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 {}
Run Code Online (Sandbox Code Playgroud)

hello.component.ts

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

预期:文本app-component为红色,文本hello-component为黑色

观察:两个文本都是红色的.为什么?

Stackblitz演示

Dav*_*vid 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}']
Run Code Online (Sandbox Code Playgroud)

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

这正是你引用的那个意思

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

Stackblitz演示

编辑:创建另一个演示,演示/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}']
})
Run Code Online (Sandbox Code Playgroud)

儿童

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

})
Run Code Online (Sandbox Code Playgroud)

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

styles: ['/deep/ .container2 {color: green}']
Run Code Online (Sandbox Code Playgroud)

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

第二届stackblitz演示