How to optionally load in the styling with my card component in angular 18?

Discussão em 'Angular' iniciado por user p, Novembro 14, 2024.

  1. user p

    user p Guest

    I'm currently trying to create a card component for my application as learning purposes. My goal to get a generic reusable card component. I do not want the div with the class class-footer be loaded in when I'm not using the card-footer directive

    card.component.ts

    import { Component, Directive } from '@angular/core';

    @Directive({
    selector: 'card-header',
    host: {
    'class': 'card-header',
    },
    })
    export class CardHeaderDirective {}

    @Directive({
    selector: 'card-content',
    host: {
    'class': 'card-content',
    },
    })
    export class CardContentDirective {}

    @Directive({
    selector: 'card-footer',
    host: {
    'class': 'card-footer',
    },
    })
    export class CardFooterDirective {}

    @Component({
    selector: 'app-card',
    standalone: true,
    imports: [],
    templateUrl: './card.component.html',
    styleUrl: './card.component.scss',
    })
    export class CardComponent {
    }



    card.component.html

    <div class="card">
    <div class="card-header">
    <ng-content select="[card-header]"></ng-content>
    </div>
    <div class="card-content">
    <ng-content select="[card-content]"></ng-content>
    </div>
    <div class="card-footer">
    <ng-content select="[card-footer]"></ng-content>
    </div>
    </div>


    here's an example of how I would use it:

    <app-card>
    <div card-header>
    <span>Header</span>
    </div>
    <div card-content>
    <span>Some content</span>
    </div>
    <div card-footer>
    <span>Sometimes I'm using this and sometimes not</span>
    </div>
    </app-card>


    The problem lays into that the class card-footer has a border-top for UI reasons. Sometimes I want to use this component but not use the card-footer. I don't want to see that border-top, but ofcourse it's now always there because of the div.

    So far I've tried using @if and optionally load in the div card-footer when checking the content using ContentChildren of ViewChild in AfterContentInit but no luck

    Continue reading...

Compartilhe esta Página