I'm trying to apply styling to a child component tag, but I can't do that.
I have child component with anchor tag.
Even though i have styling for anchor tag in the parent component, it's not applying. What's the solution for it?
Working code: http://plnkr.co/edit/CJCpV4ZbG7hdxT2AeSmt?p=preview
<a href="https://www.google.com">Google</a>
In the parent component i'm using the child component and applying styling for this child component.
Html code:
<div class="container">
<div class="test">
<testapp></testapp>
</div>
</div>
Css code:
.container{
font-family:sans-serif;
font-size:18px;
border: 1px solid black;
}
.test{
width:50%;
background-color:#f0f5f5;
}
.container:hover .test{
background-color:#e6ffe6;
}
.container:hover .test:hover{
background-color:#ffffe6;
}
.container .test a {
color: red ;
}
.container .test a:hover {
color:green;
}
We can use the :host pseudo-selector to combine a set of CSS classes to define possible child styles inside the child component itself. And then we can trigger these classes from outside by applying the style we want to the <child> host element. Angular provides a way to bind a single css class to an host element.
You should not write CSS rules for a child component elements in a parent component, since an Angular component is a self-contained entity which should explicitly declare what is available for the outside world.
It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinators (>), which are placed between two CSS selectors.
It's because by default components have view encapsulation (shadow dom). To disable this behavior, you can leverage the encapsulation
attribute, as described below:
import {Component, ViewEncapsulation} from '@angular/core'; import {TestApp} from 'testapp.component.ts'; @Component({ selector:'test-component', styleUrls: ['test.component.css'], templateUrl: './test.component.html', directives:[TestApp], encapsulation: ViewEncapsulation.None // <------ }) export class TestComponent{ }
See this plunkr: http://plnkr.co/edit/qkhkfxPjgKus4WM9j9qg?p=preview.
When using the styleUrls property, the styles are local to the one component, not to its children. So I made two changes: 1) Moved the styleUrls to the testapp component. 2) Moved the div to the testapp component.
import {Component} from '@angular/core';
@Component({
selector:'testapp',
styleUrls: ['./test.component.css'],
template: `
<div class="test">
<a href="https://www.google.com">Google</a>
</div>
`
})
export class TestApp{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With