ng-deep¶
Rule¶
Using :ng-deep (or the deprecated /deep/ and >>> selectors) in Angular is generally not recommended for several
important reasons:
- Officially deprecated - The
:ng-deepselector is officially deprecated and may be removed in future Angular versions without replacement. - Breaks component encapsulation - It pierces through Angular's view encapsulation, which defeats one of the core benefits of using components in the first place. Unpredictable scope - The selector doesn't just target child components but can potentially affect any matching element in the application, leading to unexpected style conflicts.
- Maintenance challenges - Code using :ng-deep is harder to maintain as it creates implicit dependencies between components that aren't obvious from the component hierarchy.
- Performance implications - Breaking encapsulation can impact Angular's ability to optimize rendering.
Example¶
🚨 DON’T¶
::ng-deep .floating-footer {
@extend %display-flex-center;
@include size(100%, 64px !important, 1366px);
justify-content: space-between;
::ng-deep .action-container {
@extend %display-flex-center;
@include size-2();
justify-content: flex-end;
padding: 0 3%;
box-sizing: border-box;
}
}
✅ DO¶
You should either :
- Use global styles (in
styles.scssfile) for styling third-party libraries:
.mat-dialog-container {
border-radius: 8px !important;
}
.custom-modal .mat-dialog-title {
color: #007bff;
}
- Use
ViewEncapsulation.Noneto disable the default view encapsulation and make the component's styles global:
@Component({
selector: "app-global-styles",
templateUrl: "./global-styles.component.html",
styleUrls: ["./global-styles.component.scss"],
encapsulation: ViewEncapsulation.None,
})
export class GlobalStylesComponent {}
- Use
:host-context()selector to style components based on ancestor classes:
:host-context(.dark-theme) .button {
background-color: #333;
color: #fff;
}
:host-context(.large-layout) .button {
padding: 12px 24px;
font-size: 16px;
}
- Use content projection to allow parent components to provide styled content: