简体   繁体   中英

Angular multi-line list click anywhere to navigate

So this might be simple but I'm having a hard time making a list with two rows of data that allows the user to click anywhere on the entire list item to navigate. I currently have this:

<mat-nav-list>
  <h3 matSubheader>Recent</h3>
  <mat-list-item *ngFor="let book of recentBooks$ | async">
      <a matLine routerLink="/book/{{book.id}}"><strong>{{book.title}}</strong></a>
      <p matLine>{{book.description}}</p>
  </mat-list-item>
</mat-nav-list>

This mostly works but clicking the line with the book.description doesn't navigate. I've tried using the a outside like so:

<mat-nav-list>
  <h3 matSubheader>Recent</h3>
  <mat-list-item *ngFor="let book of recentBooks$ | async">
    <a routerLink="/book/{{book.id}}">
      <p matLine><strong>{{book.title}}</strong></p>
      <p matLine>{{book.description}}</p>
    </a>
  </mat-list-item>
</mat-nav-list>

But then the list items don't display correctly. I tried adding the routerLink property to both lines and that works but I don't think it's the correct way.

Is there a more elegant way to accomplish this that I'm missing?

try to add routerLink="/book/{{book.id}}" in mat-list-item tag and remove anchor tag

this might work

You can try below code it's work for me

<h3 matSubheader>Recent</h3>
<mat-list-item>
 <a [routerLink]="['/book',book.id]">
   <p matLine><strong>book</strong></p>
   <p matLine>This is a book</p>
 </a>
</mat-list-item>
</mat-nav-list>```

Got it to work. Moved made line with *ngFor just a div , then put the mat-list-item inside with the routerLink :

<mat-nav-list>
  <h3 matSubheader>Recent</h3>
  <div *ngFor="let book of recentBooks$ | async">
    <a mat-list-item routerLink="/book/{{book.id}}">
      <p matLine><strong>{{book.title}}</strong></p>
      <p matLine>{{book.description}}</p>
    </a>
  </div>
</mat-nav-list>

I don't know if there's any negatives to not having the immediate children of a mat-nav-list be mat-list-item's but it seems to look ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM