Angular 4 Material table highlight a row

后端 未结 7 1713
栀梦
栀梦 2020-12-08 06:14

I\'m looking for a good way to highlight the whole a row in md-table.
Should I do directive or what?



        
7条回答
  •  一生所求
    2020-12-08 07:04

    In the table overview examples page they explain the SelectionModel for handling selections - which incidentally also handles multi-selection.

    selection is a SelectionModel defined in your component. I couldn't find any actual documentation for this but the implementation is extremely simple.

    selection = new SelectionModel(false, null);
    

    The first parameter is allowMultiSelect, so to allow multiple items to be selected at once set it to true. When false the selection model will deselect any existing values when you set a new value.

    Then add a click event to select() the row and create your own css class for when the row is selected.

       
            ...
    
            
    
        
    

    The css class I added is below (the sample doesn't mention styling yet) and then you just need to add to your css

    .mat-row {
       min-height: 65px;
    
       &.selected {
           background: #ffffdffffd;
       }
    }
    

    If your background color is too dark you'll need to add styles yourself to invert the text color.

    To handle selection use the onChange event of selection.

        // selection changed
        this.selection.onChange.subscribe((a) =>
        {
            if (a.added[0])   // will be undefined if no selection
            {
                alert('You selected ' + a.added[0].fullName);
            }
        });
    

    Or alternatively the selected items are in this.selection.selected.

    I'm hoping mat-table gets improved for common cases like this and they don't just leave everything up to the developer. Things like keyboard events etc. would be nice to be handled automatically with respect to the selection model.

提交回复
热议问题