Home > front end >  Angular Material Expansion Panel Header with Input
Angular Material Expansion Panel Header with Input

Time:02-10

I have an angular 12 application using Angular Material components. I have an Expansion Panel which in the header has an Input.

<mat-expansion-panel  *ngFor="let segmentGroup of segmentGroups">
            <mat-expansion-panel-header>
                    <mat-form-field appearance="outline" >
                        <input matInput [(ngModel)]="segmentGroup.name" (change)="segmentGroup.isDirty = true" (click)="$event.stopPropagation();">
                    </mat-form-field>
                    <button mat-icon-button *ngIf="segmentGroup.isDirty" (click)="Save()">
                        <mat-icon>save</mat-icon>
                    </button>
            </mat-expansion-panel-header>

I want top be able to edit the value that is within the Header. Original issue was when you clicked into the Input it would expand and collapse the Expansion panel. The onclick stop propagation fixed that issue. However, the current issue is you cannot enter a space using the spacebar. The spacebar causes the Expansion Panel to expand and collapse. How can I prevent this behavior and allow spaces within the input.

CodePudding user response:

You can stop the spacebar event propagation by fetching the spacebar keydown-event and then using event.stopPropagation() to stop it from collapsing the mat-expansion:

<mat-form-field appearance="outline" >
          <input matInput [(ngModel)]="name" (click)="$event.stopPropagation();" (keydown)="handleSpacebar($event)">
</mat-form-field>
handleSpacebar(event) {
    if (event.keyCode === 32) {
      event.stopPropagation();
    }
   }

or if you to do template only solution then you can directly do it in the template by binding to the keyDown event.

  <mat-form-field appearance="outline" >
          <input matInput [(ngModel)]="name" 
           (click)="$event.stopPropagation()" 
           (keydown.Space)="$event.stopImmediatePropagation()"
          >
  </mat-form-field>
  • Related