I have a component (my-card-component) which is made up of a mat-card with the classes .my-card. I use this component inside two other components. In component "A" I need .my-card to be 380px width, and in component B I need .my-card to be 100% width. The app starts in component A and .my-card is 380px width. Then I navigate to component B and .my-card has 100% width, but if I go back to component A, it doesn't apply the 380px width, instead it keeps the 100% width of component B. I've tried several options, including ::ng-deep .my-card, but I can't get it to apply the width correctly, can someone help me?
my-card-component HTML
<mat-card >
my-card-component CSS
.my-card {
cursor: pointer;
transition: none !important;
box-shadow: 1px 2px 8px rgba(31, 31, 31, 0.08);
}
component A HTML
<app-my-card-component></app-my-card-component>
component A CSS
::ng-deep .my-card {
width: 380px !important;
}
component B HTML
<app-my-card-component></app-my-card-component>
component B CSS
::ng-deep .my-card {
width: 100% !important;
}
CodePudding user response:
place :host
before ::ng-deep
like :host ::ng-deep .my-card
for a
:host ::ng-deep .my-card {
width: 380px;
background-color: blue !important;
}
for b
:host ::ng-deep .my-card {
width: 100%;
background-color: aqua !important;
}
CodePudding user response:
You shouldn't use ::ng-deep since it has been deprecated long time ago.
Instead of ng-deep you should use viewEncapsulaton.None and set for each component a specific class.
Here is the solution on stackBlitz.
With proper css selectors you can make the classes disappear and stop overwriting everything.
with .class1 > * > .class2, you render your rules only if every class is rendered and select class2 no matter what is the cointainer.
CodePudding user response:
Try this https://stackblitz.com/edit/angular-ivy-onxbdb?file=src/app/b/b.component.html
The key is to pass in an additional class to the my-card component
component html
<app-my-card [extraClassToApply]="'my-card-b'"></app-my-card>
my-card.component.ts
export class MyCardComponent {
@Input() extraClassToApply = "";
constructor() { }
}
my-card.component.html
<mat-card [ngClass]="extraClassToApply"></mat-card>