Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular Material Expansion Panel Header with Input

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 class="mt-2 mat-elevation-z4" *ngFor="let segmentGroup of segmentGroups">
            <mat-expansion-panel-header>
                    <mat-form-field appearance="outline" class="w-25 tableInput">
                        <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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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" class="w-25 tableInput">
          <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" class="w-25 tableInput">
          <input matInput [(ngModel)]="name" 
           (click)="$event.stopPropagation()" 
           (keydown.Space)="$event.stopImmediatePropagation()"
          >
  </mat-form-field>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading