Angular Material Table rowspan columns based on dataSource object array property size

前端 未结 4 1923
梦如初夏
梦如初夏 2020-12-15 23:11

Even now in version 7.2 of Angular Material, I can\'t seem to find examples on how to use rowspan on mat-table and keep the component functionality.

This is how far

4条回答
  •  借酒劲吻你
    2020-12-15 23:22

    There are some tricks to make this work. The other answers already got it, but I'll try a different approach.

    Let's say that your data is as it follows (I took it from one of the other answers):

    elements = [
        { id: 1, name: 'Hydrogen', weight: 1.0079, descriptions: ['row1', 'row2'] },
        { id: 2, name: 'Helium', weight: 4.0026, descriptions: ['row1', 'row2', 'row3'] },
        { id: 3, name: 'Lithium', weight: 6.941, descriptions: ['row1', 'row2'] }
    ]
    

    If we would show just one of this elements, we should write:

    ID Name Weight Descriptions
    1 Hidrogen 1.0079 row1
    row2

    And this will give us:


    Now, if we want to iterate the data, there are some things that we have to change.

    Trick 1

    If we use the *ngFor inside the tr tag, the table will crash. Instead, we just have to use it inside a ng-container tag.

    Trick 2

    We have to change the rowspan to [attr.rowspan].

    Trick 3

    The rows must have a separete iterator, but we already got the first element. So we have to make this separete iteration (with another *ngFor) but just show it if the index is above 0.

    
          
    ID Name Weight Descriptions
    {{e.id}} {{e.name}} {{e.weight}} {{e.descriptions[0]}}
    {{d}}

    And, finally, we have:

提交回复
热议问题