Is there a way to modify the parent CSS of elements like <mat-menu> within a standalone component without causing any CSS leakage into the global styles?

Recently, I've been working on customizing the CSS for <mat-menu>, specifically in an Angular Standalone Component.

So far, I've attempted to tweak it using the :ng-deep selector. Unfortunately, this method results in the CSS bleeding into the global styles, which is not ideal.

<button
    [matMenuTriggerFor]="menu"
    (menuOpened)="isMenuOpened = true;"
    (menuClosed)="isMenuOpened = false;"
    class="button"
    [ngClass]="{
        'button-red': hasCheckedFilter(),
    }">
    <ng-template 
        #title
        let-count="count"
        [ngTemplateOutlet]="title"
        [ngTemplateOutletContext]="{ count: checkedFiltersLength() }">
        <ng-container [ngSwitch]="count">
            <ng-container *ngSwitchCase="0">
                <span>Tipe Dokumen</span>
            </ng-container>
            <ng-container *ngSwitchCase="1">
                <span>{{ formatFirstCheckedFilter() }}</span>
            </ng-container>
            <ng-container *ngSwitchDefault>
                <span>Tipe Dokumen ({{ count }})</span>
            </ng-container>
        </ng-container>
    </ng-template>
    <mat-icon
        [fontIcon]="isMenuOpened ? 'expand_more' : 'expand_less'"></mat-icon>
</button>
<mat-menu #menu="matMenu" class="dashboardPelacakKebijakanFilterMenu"
    (click)="$event.stopPropagation()">
    @for (filter of filters(); track filter.type) {
        <a
            (click)="$event.stopPropagation(); toggleFilter(filters, filter.type)"
            class="dashboardPelacakKebijakanFilterMenu__button"
            routerLink="." [queryParams]="filters() | formatFiltersTipeDokumenToQueryParams: filter.type: filter.checked: activatedRoute.snapshot.queryParams">
            <div>
                <span
                    class="dashboardPelacakKebijakanFilterMenu__button__type">{{ filter.type }}</span>
                <mat-icon
                    [fontIcon]="filter.checked ? 'check_box' : 'check_box_outline_blank'"
                    class="dashboardPelacakKebijakanFilterMenu__button__icon"></mat-icon>
            </div>
        </a>
    }
</mat-menu>
.button {
    // Layout
    display: flex;
    gap: 0.25rem;
    align-items: center;
    padding: 0.5rem 0.75rem;

    // Style
    border-radius: 62.5rem;
    border: 1px solid var(--Color-Gray-gray20, #EAECF0);
    background: var(--Color-Gray-gray5, #FCFCFD);

    ...
}

// temporary solution.
// ng-deep is deprecated. 
::ng-deep .mat-mdc-menu-panel.dashboardPelacakKebijakanFilterMenu {
    ...

import { Component, OnInit, Signal, WritableSignal, computed, signal } from '@angular/core';
import { MatMenuModule } from '@angular/material/menu';
import { MatIconModule } from '@angular/material/icon';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { FilterTipeDokumen, FilterTipeDokumenType } from '../../../domain/entities/components/dashboard-pelacak-kebijakan-filter-tipe-dokumen/filter-tipe-dokumen';
import { FormatFiltersTipeDokumenToQueryParamsPipe } from '../../pipes/format-filters-tipe-dokumen-to-query-params/format-filters-tipe-dokumen-to-query-params.pipe';
import { NgClass, NgSwitch, NgSwitchCase, NgSwitchDefault, NgTemplateOutlet } from '@angular/common';

@Component({
  ...

Answer №1

To ensure the proper rendering of classes, it is recommended to enclose the styles within a parent class called

dashboardPelacakKebijakanFilterMenu
and transfer them to the file named global-styles.scss. This approach will apply the classes exclusively to the popup, avoiding any conflicts with other dropdowns by assigning distinct classes.

Below is an illustration exemplifying this concept:

global-styles.scss

/* Insert application styles & imports in this document */
@import '~@angular/material/prebuilt-themes/indigo-pink.css';

.mat-mdc-menu-panel.dashboardPelacakKebijakanFilterMenu {
  border-radius: 0.75rem;
  border: 1px solid var(--Color-Gray-gray20, #eaecf0);
  background: #fff;
  .mat-mdc-menu-content {
    display: flex;
    flex-direction: column;
    padding: 0;
  }
}
...

component

import {
  Component,
  OnInit,
  Signal,
  WritableSignal,
  computed,
  signal,
} from '@angular/core';
…

For more details and implementation, refer to the following StackBlitz project.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to float <aside> to the left of <article> for proper alignment?

tldr; I'm attempting to position the aside-section to the left of the article-section (similar to a sidebar/side column), but my "float" property doesn't seem to be working at all. Is there a way to achieve this without modifying the HTML code an ...

Ensuring Commitments in the ForEach Cycle (Typescript 2)

Having trouble with promise chains after uploading images to the server in Angular 2 and Typescript. Let's come up with some pseudo-code: uploadImages(images):Promise<any> { return new Promise((resolve, reject) => { for (let imag ...

Encountering an issue in Angular 4 AOT Compilation when trying to load a Dynamic Component: Error message states that the

My Angular application is facing challenges when loading dynamic components. Everything works smoothly with the JIT ng serve or ng build compilation. Even with AOT ng serve --prod or ng build --prod, I can still successfully build the application. Lazy loa ...

Discover the method of sending individual row data to a component using *ngFor in Angular 4

I need assistance with Angular as I am not very experienced in it. Here is the HTML code that I have: <tbody> <tr *ngFor="let data of employeeFilterLists"> <td>{{data.Code}}</td> <td (clic ...

Tips for transferring data between connected observers

Challenging Scenario: Whenever a source Observable emits an event, it triggers a sequence of API calls and Angular services. Some of these invocations rely on previous results. For instance, the source Observable startUpload$ initiates a series of interde ...

Ionic icons encountered an error due to the restriction imposed by the 'Content Security Policy'

Unexpected changes have occurred recently. Out of nowhere, an error has surfaced in my Ionic app related to ion-back-button and other ion icons as well. Here's the error message: Refused to connect to 'data:image/svg+xml;utf8,<svg xmlns=&apo ...

Unable to store object data within an Angular component

This is a sample component class: export class AppComponent { categories = { country: [], author: [] } constructor(){} getOptions(options) { options.forEach(option => { const key = option.name; this.categories[k ...

Look at the child component within the latest version of Angular

I'm diving into the world of Angular. What is the optimal way to configure the new Angular 8 view child? @ViewChild('example', {read: ElementRef, static: false}) public example: ElementRef; or @ViewChild('example', {read: ElementR ...

Update the image source dynamically upon the opening of an accordion in Angular

I have the following HTML code snippet in my file: <div class="col-md-3 col-sm-2 col-2 collapsedData" > <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-con ...

Attempting to incorporate real-time search functionality into an input field

Looking to incorporate live search functionality in a text box, with the options being fetched from the server. If an item is not available, it should be added dynamically. For example, if typing "gre" and selecting that word, it should automatically be ad ...

Creating stylistic layouts for text using CSS

After spending the last hour designing a web page, I am stuck on a particular issue that I just can't seem to solve. I need to write several paragraphs while adhering to two specific constraints: 1) The div in which the text resides must be centered ...

Text wrapped automatically to display multiple lines with spacing between each highlighted line

Question about CSS formatting and spacing. I need to automatically break sentences into new lines based on the width of the container. For example, a sentence like: This is a sentence should be displayed as: This is<br>a sentence I am trying ...

The discrepancy in font size behavior between local and production environments is noticeable when using a React-Bootstrap Navbar

My website on Heroku is using <Navbar> from React-bootstrap, but I'm facing an issue where the text within the <Navbar> appears much larger in production compared to locally. Can anyone help me figure out why this might be happening? The t ...

Angular material is experiencing an issue where content is being cut off or

I am currently working on a project using AngularJS for a web application. I have encountered an issue where some of the content in the md-content element is being clipped. For instance, the body tag has the style: overflow: hidden, and the child md-conte ...

I am interested in showcasing a card when it is hovered over

I am having trouble with a hover effect to display a hidden card. I have two div elements, one is labeled single-album and the other hide. I used the + selector to set the hide div to display none initially, but the hover effect is not working as expecte ...

I am having trouble retrieving edge labels asynchronously in jsplumb. When I subscribe to the observable to retrieve the labels of the edges, I am receiving undefined. Is there a solution to this issue

I need to retrieve data from the backend and use it as labels for the edges instead of +N. Can someone assist me in resolving this issue? Thank you in advance. Trying to asynchronously fetch jsplumb graph edge labels ...

Use CSS to apply word-breaking to the <p> element that contains an <a

I am working with HTML and have the following code: <p>Read the <a target="_blank" class="highlight" href="www.url.com">'Design Network Hierarchy and Settings'</a> chapter in your version's user guide to learn how to creat ...

Enhance the appearance of your PrimeNG dropdown by incorporating custom font sizes and trigger icon sizes

Struggling with customizing the font size and dropdown trigger icon styling of a PrimeNG dropdown in my Angular TypeScript application. The documentation for PrimeNG's styling options is unclear, making it difficult to achieve the desired customizatio ...

Automatically close dropdown when clicking on another option

Currently, I'm working on creating a responsive dropdown navigation bar using vanilla JavaScript. My goal is to have only one dropdown menu open at a time when clicked in mobile view. Here's the JavaScript code snippet: dropbtns.forEach(link =&g ...

Unable to modify border-spacing in the default User Agent stylesheet

I am encountering an issue where I am unable to override the border-spacing in the User Agent style sheet within Chrome. Currently, it is set to 2px, but I am trying to change it to 0px. Despite successfully overriding the border-collapse property, the bor ...