karasekv
karasekv

Reputation: 67

How to use in Angular Material List an Item component

I'm trying to migrate Angular code from Bootstrap to Material design. I need to show a list of items (for example Cars). I have a car-list component and car-item component. I want to keep it separate if it's possible.

Unfortunately the resulting list of 10 items is presented as 10 square boxes on one row instead of expected 10 rows.

My question is: Can I use a separate component inside a <mat-list-item>?

All angular material examples I came across showed mat-list-item with ngFor directive and item template code inside node. That means to move Item functionality into a List.

Bootstrap version

car-list-component.html

<div class="row">
  <div class="col-xs-12">
    <router-outlet></router-outlet>
    <app-car-item
      *ngFor="let carItem of cars"
      [car] = "carItem"
    ></app-car-item>
  </div>
</div>

car-item.component.html

<div>
  <div>
    <a (click)="carDetail(car.id)">
      <span>{{ getMakeLabel(car.make)}} : {{car.carModel.modelName}} </span>
    </a>
  </div>
  <div>
    <a (click)="remove(car)"><i class="material-icons">delete</i>
    </a>
  </div>
</div>

My Angular Material version with a separate item template

car-list.component.html

<div>
<mat-list role="list">
  <mat-list-item>
    <router-outlet></router-outlet>
    <app-car-item
      *ngFor="let carItem of cars"
      [car] = "carItem"
    ></app-car-item>
  </mat-list-item>
</mat-list>
</div>

car-item.component.html does not change.

Angular Material Example with 'inline' item template.

This is presented in all examples and tutorials on Angular Material. It would work for me, but as I said before if Item(car) is a more complex object than in this example then I want to keep it separately.

car-list.component.html

<mat-list>
    <mat-list-item *ngFor="let car of cars">
      <a style="cursor: pointer;" (click)="carDetail(car.id)">
       <span>{{ getMakeLabel(car.make)}} : {{car.carModel.modelName}} </span>
      </a>
    </mat-list-item>
</mat-list>

Upvotes: 2

Views: 9121

Answers (1)

Prashant Biradar
Prashant Biradar

Reputation: 323

You can add mat-list-item as the directive to your app-car-item component. please refer https://stackblitz.com/edit/angular-blzeb1

<mat-list role="list">
    <app-car-item mat-list-item
      *ngFor="let carItem of cars"
      [car] = "carItem"
    ></app-car-item>
 </mat-list>

Upvotes: 3

Related Questions