How to style projected content in an Angular wrapper component?

Discussão em 'Angular' iniciado por AbVog, Fevereiro 6, 2025.

  1. AbVog

    AbVog Guest

    I am drafting a web app with Angular 19 and Material, and I came across an issue with buttons arranged in a toolbar.

    The issue is that I can't get a CSS rule to work on the buttons so that the specification margin-right: 8px applies to each button.

    My intention

    Since I'm using Material and it defines no spacing between buttons in a toolbar, I've chosen to create a component that will wrap a mat-toolbar and apply a specific CSS class to it so that buttons are spaced. My component's template is this:

    <mat-toolbar class="app-toolbar">
    <ng-content></ng-content>
    </mat-toolbar>


    The accompanying CSS is:

    .app-toolbar {
    button {
    margin-right: 8px;
    }
    }


    The issue

    No matter how I express the selector, be it button, &>button or button+button, I can't seem to affect the right margin of any buttons in the toolbar. Here is the rendered HTML:

    <app-toolbar _ngcontent-ng-c1959984292="" _nghost-ng-c2441739416="">
    <mat-toolbar _ngcontent-ng-c2441739416="" class="mat-toolbar app-toolbar mat-toolbar-single-row">
    <button _ngcontent-ng-c1959984292="" mat-raised-button="" mat-ripple-loader-class-name="mat-mdc-button-ripple" class="mdc-button mdc-button--raised mat-mdc-raised-button mat-unthemed mat-mdc-button-base">
    …


    There's obviously something at play that evades me. It seems like the styling does not apply to projected content but I haven't found that specific info in the official documentation. I've found "You cannot add directives, styles, or arbitrary attributes to <ng-content>." from https://angular.dev/guide/components/content-projection but that's about it.

    The workaround I ended up using

    Since mat-toolbar has display: flex, I ended up adding column-gap: 8px. The CSS is now:

    .app-toolbar {
    column-gap: 8px;
    padding:0;
    }


    Even though I have a solution to this specific use case, I still want to understand what's at play. I hope someone knowledgeable has an answer for me. Thx.

    Continue reading...

Compartilhe esta Página