【问题标题】:How to style recursively nested child component from parent component如何从父组件中递归嵌套子组件
【发布时间】:2018-03-04 03:05:06
【问题描述】:

这是我的父组件 html

<div class="col-md-6">
          <div class="categories">
            <div class="title">All Categories</div>
            <nested-cat [data]="data" [key]="key" (action)="onClicked($event)" class="cat-container"></nested-cat>
          </div>
      </div>
    </div>

这是我的子组件 html

<ul class="categorys" *ngIf="items.length">
  <li class="cat"  *ngFor="let item of items">
    <div class="content">
      <span class="name">{{item.name}}</span>
      <span class="action">
          <button md-icon-button><md-icon color="primary" (click)="hello('hello')">edit</md-icon></button>
          <button md-icon-button><md-icon color="warn">delete</md-icon></button>
      </span>
    </div>
    <nested-cat *ngIf="item[key].length" [key]="key" [data]="item[key]" (action)="onClicked($event)"></nested-cat>
  </li>
</ul>

我正在关注thisthis 链接,发现:host(selector):host-context(selector) 用于定位父子组件。但我无法弄清楚如何在我的情况下实施。

我已将这些 css 用于父级:

:host ::ng-deep nested-cat{
    width: 100%;
    padding:0;
  }

这很好,但是当我尝试定位第一个 ul 元素时,样式将应用于所有 ul 元素。

:host(nested-cat) ::ng-deep ul:first-of-type{
    padding:0;//this will apply to all ul 
}

如何定位第一个嵌套猫的第一个孩子(即 ul)并将填充设置为 0?

更新:

这里是一个 plunkr https://plnkr.co/edit/fU0WLIwh9V6Euoz43hvS?p=preview

终于成功了:

  :host ::ng-deep .categories>nested-cat>ul{
      padding: 0 4px;
  }

【问题讨论】:

标签: css angular


【解决方案1】:

这将解决:

:host ::ng-deep .content{
  width: 100%;
  margin-left:-40px
}

DEMO

【讨论】:

    【解决方案2】:

    这个选择器应该可以解决问题,至少对于这个特定的例子:

    .bg > nested-cat > ul {
        padding-left: 0;
    }
    

    &gt; 是直接子选择器。它只选择匹配的直接子元素,而不是树下的任何后代。

    【讨论】:

    • 感谢您的回答,但这不起作用。你能在plnkr中说明吗?
    猜你喜欢
    • 2018-10-25
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2017-03-18
    • 2023-03-24
    • 1970-01-01
    • 2017-08-23
    相关资源
    最近更新 更多