Issue
I'm trying to apply a css file to components located in a child component, by importing the css file within the child's css file, and to affect the nested components using:encapsulation: ViewEncapsulation.None
But by setting encapsulation
to none
, not only does it affect the nested components within the child component, but it affects the parent component as well, as the imported css file now applied to the parent component as well.
My question is why setting encapsulation
to none
in a child component affects the parent as well?
Solution
Setting the ViewEncapsulation to none will result in the styles propagating across other modules and components, thus it might not be suitable if you only want them to be applied within the module, or the parent/child components.
If you wish to apply the CSS only for that component and its 'nested' child components, you can try defining a shared css, which will be shared amongst the main component and the child component. Do not set ViewEncapsulation to None. This is how you can structure the files within that module.
|--parent
|--shared
|-- shared.css
|--components
|--child
|--child.component.ts
|--child.component.css
|--parent.module.ts
|--parent.component.ts
|--parent.component.html
|--parent.component.css
Then on the @Component type decorators near the top of both of your parent and child component, you can include the relative/absolute path of the css files required. As you can see, shared.css
is included in both components, and the styles will only be encapsulated to these compenents.
child.component.ts:
@Component({
selector: 'child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css', '../../shared/shared.css'],
})
And on your parent.component.ts,
@Component({
selector: '',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css', './shared/shared.css'],
})
Answered By - wentjun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.