Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind an click event for mat-step-header

I want to trigger a function when user clicks on mat-step-header

I've tried adding (click) on <ng-template matStepLabel><span (click)="triggerClick()">step 1</span></ng-template> but it's triggering only on the click of label which will not be helpful for my case.

I want to trigger a function when user click on any of the mat-step-header if it returns the index of clicked step it will be helpful.

like image 877
Hemanth Paluri Avatar asked Aug 09 '19 11:08

Hemanth Paluri


2 Answers

Probably you have solved it now, but just in case anyone else is seeking for a simple solution:

Simply put an overlay <div> on top of the stepper header like this below:

<ng-template matStepLabel>
  <div class="stepper-header-overlay" (click)="yourClickHandler()"></div>
  some header text
</ng-template>

And setup the header style:

.stepper-header-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
like image 59
Neo Liu Avatar answered Oct 08 '22 19:10

Neo Liu


From the docs it doesn't look like there's a direct way to do this. The only eventEmitter that could help you would be selectionChange(). We can use this along with a (click) event to get the selectedIndex on click.

We can use selectionChange() to get the index of the selected tab. As per the docs

selectionChange() is the event emitted when the selected step has changed

In your HTML

<mat-horizontal-stepper #stepper (selectionChange)="setIndex($event)" (click)="triggerClick($event)">
  <!-- Add your steppers here -->
</mat-horizontal-stepper>

and in your component

// Set default tab value to index so you don't get undefined if user clicks default tab initially
selectedIndex: number = 0;

setIndex(event) {
  this.selectedIndex = event.selectedIndex;
}

triggerClick(event) {
  console.log(`Selected tab index: ${this.selectedIndex}`);
}

Here is a working example on StackBlitz.

like image 6
nash11 Avatar answered Oct 08 '22 19:10

nash11