Search code examples
angulareventsangular-material2property-binding

Property Binding will not trigger in angular


i like to detected the changeEvent when property "completed" is changing and call onChange(). https://material.angular.io/components/stepper/overview

import {Component, ViewChild} from '@angular/core';
import {MatStepper} from "@angular/material/stepper";

@Component({
  selector: 'app-mat-stepper',
  styleUrls: ['./mat-stepper.component.css'],
  template: `<div class="mat-card-div">
  <mat-vertical-stepper #mystepper [linear]=true>
    <mat-step [completed]="this.comp" (completed)="onChange()">
      <ng-template matStepLabel>Test1</ng-template>
      test 1
    </mat-step>

    <mat-step>
      test 2
      <ng-template matStepLabel>Test2</ng-template>
    </mat-step>
  </mat-vertical-stepper>
  <button (click)="test()">test</button>
</div>`
})
export class MatStepperComponent {
  @ViewChild('mystepper') myStepper!: MatStepper|undefined;
  comp:boolean=false;

  constructor() {
  }

  test()
  {
      this.comp=true
  } 

  onChange()
  {
     this.myStepper?.next()
  }
}

Thanks for your help.


Solution

  • Unfortunately for you, according to Angular Material Docs, there is no @Output for completed event, its only @Input to mark whether step is completed.

    You will need to check this manually from your component.

    import {Component, ViewChild} from '@angular/core';
    import {MatStepper} from "@angular/material/stepper";
    
    @Component({
      selector: 'app-mat-stepper',
      styleUrls: ['./mat-stepper.component.css'],
      template: `<div class="mat-card-div">
      <mat-vertical-stepper #mystepper [linear]=true (selectionChange)="detectLastStep($event)">
        <mat-step [completed]="this.comp">
          <ng-template matStepLabel>Test1</ng-template>
          test 1
        </mat-step>
    
        <mat-step>
          test 2
          <ng-template matStepLabel>Test2</ng-template>
        </mat-step>
      </mat-vertical-stepper>
      <button (click)="test()">test</button>
    </div>`
    })
    export class MatStepperComponent {
      @ViewChild('mystepper') myStepper!: MatStepper|undefined;
      comp:boolean=false;
    
      constructor() {
      }
    
      test()
      {
          this.comp=true
      } 
    
      detectLastStep(_event: StepperSelectionEvent)
      {
        if (...doYourCondition)
          this.myStepper?.next()
      }
    }
    

    For more elaborate documentation about MatStepper, check CDK https://material.angular.io/cdk/stepper/api#StepperSelectionEvent