【问题标题】:CSS selector for first child component of another Angular component另一个 Angular 组件的第一个子组件的 CSS 选择器
【发布时间】:2017-05-09 11:43:25
【问题描述】:

在 Angular 中,我需要使用一些 CSS (SASS) 规则选择父组件的第一个子组件。我有一个作为一个组件的项目列表,然后我有列表项,它们本身就是组件。所以它的结构如下:

<product-list>
    <list-item />
    <list-item />
    <list-item />
</product-list>

每个组件的 CSS 规则仅与该组件隔离,因此我无法使用第一个子选择器来选择第一个列表项。

换一种说法,因为 product-list SASS 文件中的规则不适用于其子项,而 list-item SASS 文件中的规则不适用于其父项,所以我不能使用 product-list:first-child在两个 SASS 文件中的任何一个中,因为任何一个文件都需要引用列表父级和列表子级。

首先,我想知道这个 CSS 规则隔离叫什么。这是一个不错的功能,但它在这里阻止了我。

我可以在全局 SASS 中编写规则,但这似乎不是最好的方法。

有人可以告诉我真正的 Angular 方法吗?

【问题讨论】:

  • 听起来你需要一个有穿透力的 css 组合器。 “隔离”称为“封装”。

标签: angular css-selectors


【解决方案1】:

你去https://plnkr.co/edit/FPqx6m12tkmMFlf5LvJl?p=preview

@Component({
    selector: "my-li",
    styles:[`
     :host {
         color:blue

     }

    `]
    template: `
        <li>This is my li</li>
    `
})
export class MyLi {

}


@Component({
    selector: "navbar",
    directives: [NgFor,MyLi], 
    styles: [`
        my-li:nth-child(2){
          color: yellow;
        }
    `],
    template: `
        <h2>Democratic Party presidential candidates</h2>
        <ul>
          <my-li *ngFor="#item of items; #i = index">{{item}} {{i}}</my-li>
        </ul>
    `
})
export class Navbar {
    items: Array<String>

    constructor() {
      this.items = [
        "Hillary Clinton",
        "Martin O'Malley",
        "Bernie Sanders"
      ]
    }

}

注意:这里使用的是旧版本的 Angular2 ,在新版本中 @component 中没有指令数组,所以不要混淆,看看样式就行了。

【讨论】:

  • 我花了一些时间才理解,但现在我明白了::host 选择器是这里的关键。谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多