Trigger event on re-selecting same value on mat-select

前端 未结 2 1657
孤城傲影
孤城傲影 2021-01-18 18:23

I\'m working on a mat-table which implements pagination, filtering, selection, etc. I have this mat-select on one of the header columns which I use

2条回答
  •  心在旅途
    2021-01-18 19:20

    I know this is late, but I've come to find a solution.

    Normally, we would be using @Output() selectionChange to pass the selected value to a function in our .ts file and do what we want there. But this doesn't work if we select the same value.

    Solution:

    So what we need to do instead is use @Output() openedChange which will pass true (opened) or false (closed). We are interested in when we close the mat-select component. Unfortunately openedChange doesn't have direct access to the value we selected. So we simply make a member variable which is binded to the value we select, and whenever openedChange is triggered and returns false, we will use that member variable.

    Here's the basic code:

    your-component.component.html

    
      Options
      
        
          {{option.name}}
        
      
    
    

    your-component.component.ts

      selectedVariable: any;
    
      constructor() {}
    
      ngOnInit() {
        //...
      }
    
      onSelectionChange(opened: boolean) {
        if (!opened && this.selectedVariable) {
          // Do whatever you want here with `this.selectedVariable`
          console.log(this.selectedVariable);
        }
      }
    

    Note: In the onSelectionChange function, you need to make sure that something was actually selected. Because otherwise the function will continue if a user clicks on the select, and clicks away from it without selecting anything.

提交回复
热议问题