2

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>

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

@Vladimir If my answer helped you, please mark it with a decision.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.