Angular Material, using mat-card-avatar without a card

17,716

Judging from the source code, the mat-card-avatar directive does nothing more than assign the mat-card-avatar class to the directive's element, which just adds a little style to produce the avatar appearance. So there is no harm in using it outside a mat-card.

As for why was something that is general purpose made part of the MatCard component - probably because they didn't want to have to go to the extra effort of having to test and support it with other usages, and make MatCard work properly with a general purpose thumbnail. It also might have to do with the fact that Material Design specifies that as an element for Cards, although the same element is specified for Lists (and possibly elsewhere) and exists as another directive mat-list-icon (style code is a little different). Chalk it up to no-one on the team really looking after little common things like this.

One negative side of using this is that you have to import the entire MatCard module in order to use it. No problem if you are using mat-card in your application, but it adds unnecessary size to your application if you're not. It would be better to just steal the style code and create your own class.

$mat-card-header-size: 40px !default;
.mat-card-avatar {
  height: $mat-card-header-size;
  width: $mat-card-header-size;
  border-radius: 50%;
  flex-shrink: 0;

  // Makes `<img>` tags behave like `background-size: cover`. Not supported
  // in IE, but we're using it as a progressive enhancement.
  object-fit: cover;
}
Share:
17,716

Related videos on Youtube

Kunepro
Author by

Kunepro

Updated on June 19, 2022

Comments

  • Kunepro
    Kunepro about 2 years

    I just want to add a small round profile picture, I don't want it to be in a "card", and something like this actually works:

    <img mat-card-avatar src="avatar.png" alt="User Avatar">
    

    That <img> is not contained in a <mat-card> element, and even though it works I'm wondering about the legality of the solution and possible side effects. So is it ok to use a mat-card-avatar like that outside of a mat-card element?

    Also it took me a long time to find this directive, why was the avatar name-spaced as something that should be part of a card when it could generally be used in other contexts? For example I have it in a mat-toolbar.

  • ouah
    ouah over 4 years
    I ran into a similar issue - for me the avatar renders, but on first page renders it will fails if there is no mat-card in the current component stack. Re-rendering a view will render the avatar. Related issue: stackoverflow.com/questions/58864615/…
  • G. Tranter
    G. Tranter over 4 years
    Makes sense that that would happen - all the more reason to simply use your own style class.