Suraj Khanal Suraj Khanal - 27 days ago 12
CSS Question

How to style nested child component from parent component in angular 4

This is my parent component 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>


This is my child component 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>


i am following this and this links and found that
:host(selector)
and
:host-context(selector)
are used to target parent and child component. But i cannot figure out how to implement in my case.

I have used these css for parent :

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


which is working fine but when i try to target the first ul element, style is applied for all ul element.

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


How could i target the first child (i.e ul) of first nested-cat and set padding to 0?

Update:

Here is a plunkr https://plnkr.co/edit/fU0WLIwh9V6Euoz43hvS?p=preview

Finally this is working :

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


enter image description here

Answer Source

This selector should do the trick, at least for this specific example:

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

Where > is the immediate child selector. It only selects matching elements that are direct children, and not any descendants further down the tree.