Search code examples
cssangularangular-material

Angular Material List items with buttons, pretty, please


I'd like an Angular Material v18.1 List with some emphasized content and a couple of buttons, something like this:

list of contacts with actions

But when I add, say, the matListItemTitle directive to the name, things go awry:

enter image description here

I can style the elements explicitly, of course, but I thought the Angular Material List directives would be a bit more helpful. Any insights to what I'm doing wrong?

<main>
  <mat-list>
    @for (c of contacts; track c) {
    <mat-list-item>
      <mat-icon matListItemIcon>folder</mat-icon>
      <div class="contact-details">
        <!-- without matListItemTitle display is okay -->
        <div matListItemTitle>{{c.name}}</div>
        <div>{{c.email}}</div>
        <div>{{c.description}}</div>
      </div>
      <button matListItemMeta mat-stroked-button color="primary">Compose</button>
      <button matListItemMeta mat-stroked-button color="warn">Remove</button>
    </mat-list-item>
    <mat-divider></mat-divider>
    }
  </mat-list>
</main>
:host {
  width: 100%;
}

main {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 95%;
  margin: 20px;
}

mat-list {
  width: 80%;
}

mat-list-item {
  display: flex;
  flex-direction: row;
}

.contact-details {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  gap: 10px 30px;
}
import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [MatButtonModule, MatDividerModule, MatIconModule, MatListModule],
  templateUrl: './list.html',
  styleUrl: './list.css',
})
export class App {
  contacts = [
    { name: 'one', email: '1@one', description: 'The one.' },
    { name: 'two', email: '2@one', description: 'The two.' },
  ];
}

Solution

  • The main issue is that you are styling your buttons with matListItemMeta, which is why they don't come out right.

    Try wrapping matListItemMeta in a span as follows:

    <span matListItemMeta>
      <button mat-stroked-button>This is a button</button>
    </span>