Click function for mat-step event handler

Is it feasible to create a click event for the mat-step button? I want to be able to add a (click) event for each mat-step button that triggers a method. Essentially, I am looking to make the mat-step button function like a regular button.

You can find more information about mat-step here: https://material.angular.io/components/stepper/overview

Below is the code snippet I have tried:

<mat-step>
<ng-template matStepLabel (click) = "createView()">Output</ng-template>
</mat-step>

However, when I run this code, I encounter the following error:

Template parse errors: Event binding click not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("eateView()" >Output-->

Answer №1

Recently, I encountered a similar issue and found a quick fix by wrapping the step label's content in a p tag and adding the click event there. Here is an example of how you can implement it:

<mat-step>
  <ng-template matStepLabel>
    <p (click)="createView()">Output</p>
  </ng-template>
</mat-step>

Another approach is to utilize the selectionChange event in the parent stepper component for more flexibility and control:

<mat-horizontal-stepper (selectionChange)="selectionChange($event)">

You can find more information about the properties of the event emitted by visiting: https://material.angular.io/cdk/stepper/api#StepperSelectionEvent

Answer №2

Discovering what to do after a Step event can be challenging. If you find yourself in this situation, follow these steps.

Include (animationDone)

<mat-horizontal-stepper linear #stepper (animationDone)="selectionChange(stepper)">

This action will trigger once the step is completed, providing you with the index of the new step you have reached!

Answer №3

For those looking to add a click event listener to the stepper, even if the user clicks on the current step (which won't trigger the selectionChange event):

    ngAfterViewInit() {
        console.log('ngAfterViewInit is triggered');
        this.fadeOut = false;
        let elements = document.querySelectorAll('mat-step-header');
        console.log('elements: ', elements);
        if (elements) {
            elements.forEach((e, i) => {
                console.log('e', i, ': ', e);
                if (i === 0) {
                    this.ele0 = e;
                    this.click0 = e.addEventListener('click', () => this.function(i));
                }
                else if (i === 1) {
                    this.ele1 = e;
                    this.click1 = e.addEventListener('click', () => this.function(i));
                }
                else if (i === 2) {
                    this.ele2 = e;
                    this.click2 = e.addEventListener('click', () => this.function(i));
                }
            })
        }
    }

If you prefer not assigning each listener to a unique value, you can remove the if condition. However, it is recommended so that you can easily remove those listeners during destroy.

Answer №4

The (selectionChange) event is triggered after the stepper change, but I want to call a function before selectionChange.

The code below is working for me. You can try this, it will work for the entire mat-step button (due to custom CSS, you can also add CSS for the span element).

.mat-step-custom-click {
    top: 0;
    left: 0;
    width: 130px; // adjust as needed
    height: 72px; // adjust as needed
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
}


<mat-step>
    <ng-template matStepLabel>
        <div class="mat-step-custom-click" (click)="justTesting()">
            <span>YOUR LABEL</span>
        </div>
    </ng-template>
</mat-step>


justTesting(){
   if( stepper.selectedIndex ){ // you can check stepper index
      let isValid = this.CheckValidations(yourData); // check your validations
      stepper.selected.completed = isValid;
      if( isValid ){
       doSomething(); // call your function
      }
   }
}

Answer №6

Why not give this a go instead of using ng-template, try using div or span. It seems like the event is triggering. Give it a shot and inform me.

The error seems to indicate that ng-template is not firing as an event.

<mat-step>
    <ng-template matStepLabel>Done</ng-template>
    You are now done.
    <div>
      <button mat-button matStepperPrevious>Back</button>
      <button mat-button (click)="stepper.reset()">Reset</button>
    </div>
  </mat-step>

Here is an example I copied from the link you sent. Give this button a try.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When working with Angular/Typescript, the error message "compilation of 'export const' is not possible

Embarking on creating my very own Angular library, I took the first step by adding a service without any issues. The challenge arose when I decided to move a constant to a file named tokens.ts for the service to reference. Following this change, the build ...

Troubleshooting the issue of process.nextTick not being recognized in Calgolia places.js

After successfully implementing Algolia's places.js in my Angular 7 project using NPM, I encountered an issue. I have integrated a form where one of the fields should be an input. <form [formGroup]="myForm"> <pre style="color: white; b ...

React error: The DatePickerProps generic type must have one type argument specified

Date Selection Component: import React from "react" import AdapterDateFns from '@mui/lab/AdapterDateFns'; import { LocalizationProvider } from '@mui/lab'; import { DatePicker, DatePickerProps } from '@mui/lab'; cons ...

The 'Access-Control-Allow-Origin' header can be found on the resource that was requested

I'm facing an issue while trying to connect my .net core API to an Angular application. Whenever I attempt to do so, I encounter the following error: Access to XMLHttpRequest at 'https://localhost:44378/api/recloadprime' from origin 'h ...

The 'setState' property is not found on the 'Window' type

I am encountering an issue with the code snippet in my index.tsx file let state = {}; window.setState = (changes: any) => { state = Object.assign({}, state, changes); ReactDOM.render(<App {...state} />, document.getElementById("root")); ...

The functionality of the Angular application is not compatible with Edge browser

Encountering an issue with loading my dashboard on Edge (works fine on Chrome). The page fails to load, unlike in Chrome. The problem seems to be linked to the code snippet ColorScale.js.pre-build-optimizer.js: /** * Set up color sca ...

Error: Uncaught TypeError in AuthContext in Next.js 13.0.6 when using TypeScript and Firebase integration

I'm currently trying to display a page only if the user is present in my app. Right now, the app is pretty bare bones with just an AuthContext and this one page. I had it working in React, but ran into some issues when I switched it over to TS and Nex ...

Having difficulty implementing canDeactivate or canActivate in Angular

I am currently trying to integrate the canDeActivate and canActivate functions in my Angular 4 project. However, I seem to be encountering a no provider error. Can someone please guide me on what might be wrong with my implementation or suggest a cleaner a ...

Managing business logic in an observable callback in Angular with TypeScript - what's the best approach?

Attempting to fetch data and perform a task upon success using an Angular HttpClient call has led me to the following scenario: return this.http.post('api/my-route', model).subscribe( data => ( this.data = data; ...

MasterNG - Submitting form details and uploading files with a button press

Our Angular project involves a form with various form fields along with PrimeNG FileUpload, and our goal is to send the form data along with the selected files in one go. Despite researching the documentation and numerous examples online, we couldn't ...

Struggling with sluggish performance on a certain project within VS Code

My experience with VS code has been excellent over the years, but I recently encountered a problem in one of my projects that caused a significant slowdown in performance. Strangely, other projects are working fine without any issues on VS code. I suspect ...

Guide to displaying a section of Component A within Component B

There are two components, X and Y <div class="X"> <div class="X1"></div> <div class="X2"></div> </div> <div class="Y"> <!--want to display <div class="X1"></div> here--> </div> ...

Leverage Sinon's fakeServer in combination with promises and mocha for efficient

Having an issue here: I need to test a method that involves uploading data to an AWS S3 bucket. However, I don't want the hassle of actually uploading data each time I run my tests or dealing with credentials in the environment settings. That's w ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

Steps for importing a CommonJS module that exports as a callable into TypeScript

I am dealing with a project that has a mixture of JavaScript and TypeScript files. Within the project, there is a JS library that follows this structure: module.exports = () => { // logic dependent on environment variables // then... return { ...

Steps for launching Angular 5 application using Node.js server

I have developed an Angular 5 application that retrieves data from a node.js server. I successfully deployed the application to my web server hosted by FastComet, which supports node.js, but unfortunately, the server does not seem to be functioning properl ...

Unexpected behavior with the ion-datetime time picker on an Android device

I am encountering challenges with a Date and Time entry feature in my Angular/Ionic application that involves date pickers. When I tap on the Time field, the time picker opens. Everything works perfectly in my browser - I can select a time, spin the value ...

Exclude the initial argument from functions listed within a JSON structure

Is there a way to create a generic type that reflects a JSON object structure, but excludes the first argument from functions while maintaining the types of other arguments? type InputType<T> = { increment: (state: T) => T, add: (state: T, cou ...

Encountering an Error: ExpressionChangedAfterItHasBeenCheckedError, whilst conditionally modifying an attribute of

One interesting approach I'm using is to conditionally add title attributes to elements. Here's an example: <div #optionEl class="option-title" [attr.title]="isTitleTruncated(optionEl) ? option.title : null"> {{option.title}} </div& ...

Ways to fix the perpetual cycle in adal-angular4 following authentication redirect

I have been working on an Angular 8 application that utilizes Microsoft Azure Active Directory authentication with adal-angular4. I've successfully set up an ASP.NET Core API linked to a client app on Azure. To configure Active Directory, I referred ...