Kunepro
Kunepro

Reputation: 428

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

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.

Upvotes: 11

Views: 19475

Answers (1)

G. Tranter
G. Tranter

Reputation: 17938

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;
}

Upvotes: 15

Related Questions