angularangular-material2transclusion

Angular 2 Material transclusion, selectors and attribute directives


I'm currently looking at the github and docs for the angular material 2.

I'm trying to buid my own components for my app following how these material components have been structured.

I'm wondering about the reasons that some selections within the component contain multiple selectors. For example, I'm looking at the mat-card on github and more importantly, mat-card-header.

<ng-content select="[mat-card-avatar], [matCardAvatar]"></ng-content>
<div class="mat-card-header-text">
  <ng-content
      select="mat-card-title, mat-card-subtitle,
      [mat-card-title], [mat-card-subtitle],
      [matCardTitle], [matCardSubtitle]"></ng-content>
</div>
<ng-content></ng-content>

The above is the html for mat-card-header which can be seen here: mat-card-header.

And here is the directive in the typescript:

@Directive({
  selector: `mat-card-title, [mat-card-title], [matCardTitle]`,
  host: {
    'class': 'mat-card-title'
  }
})
export class MatCardTitle {}

What is the benefit or reason of having these 3 selectors. mat-card-title, [mat-card-title], [matCardTitle]?


Solution

  • The benefit is a robust component library for the adopters of your package.

    In the mat-card-title example this allow users to use the directive in a way that best fits their use case. Such as...

    <mat-card-title>My Title</mat-card-title>
    <div class="mat-card-title">My Title</div>
    <div class="matCardTitle">My Title</div>
    <div mat-card-title>My Title</div>