1
votes

Dans ma forme angulaire, j'ai ajouté un événement keycode avec F2. Pourquoi ne fonctionne-t-il pas sur certaines situations?

Ce que j'ai fait: J'ai créé une page html angulaire avec un formulaire. Le formulaire comprend certaines données d'entrée avec autofocus. J'ai ajouté une touche d'événement "F2" qui déclenche un message de console.

Mon objectif: le faire fonctionner avec tous les états.

Le problème: Cet événement ne fonctionne que lorsque j'appuie sur la zone de champ de saisie puis F12 - mais cela ne fonctionne pas quand je ne suis pas au point avec la zone de saisie.

code html:

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MathService } from 'src/app/services/math.service';


@Component({
    selector: 'app-mbf-hardwood-calc',
    templateUrl: './mbf-hardwood-calc.component.html',
    styleUrls: ['./mbf-hardwood-calc.component.css']
})
export class MbfHardwoodCalcComponent implements OnInit {
    mbfValue: number;
    rowOneValue: number;
    cbm: string;
    twoFiveFourAddon = false;
    autoRenew = new FormControl();
    addonPrint = 236;


constructor(private mathService: MathService) { }

ngOnInit() {
}
// toggles between 236 and 254 modes
onChange() {
    this.autoRenew.value ? this.addonPrint = 254 : this.addonPrint = 236; // print next to switch sign
    if (!isNaN(this.mbfValue)) { this.cbm = this.mathService.mbf2cbm(this.mbfValue, this.autoRenew.value).toFixed(3); }


}
// enter key pressed event catcher
keyDownFunction(event) {
    if (event.keyCode === 113) {
        console.log('F2 pressed');
    } else if (event.keyCode === 13 && !isNaN(this.mbfValue)) {
        this.cbm = this.mathService.mbf2cbm(this.mbfValue, this.autoRenew.value).toFixed(3);
    }
}

Code dactylographié:

<body>
<div class="container">
<h1 class="header"> מחשבון עצים אמריקאים</h1>
<form #myform="ngForm" (keydown)="keyDownFunction($event)">
    <div>
        <label for="mbf" class="label">בורד פיט:</label>
        <!--input with minus not allowed -->
        <input type="number" min="0" name="mbf" [(ngModel)]="mbfValue" autofocus required #mbf="ngModel" onkeypress="return event.charCode != 45">
        <span class="error-message" *ngIf="mbf.dirty && mbf.invalid">לא הוזן מספר</span>            
        <label for="rowOne">שורה:</label>
        <input type="number" min="0" name="rowOne" [(ngModel)]="rowOneValue" autofocus required #rowOne="ngModel" onkeypress="return event.charCode != 45" placeholder="1">
        <span class="error-message" *ngIf="mbf.dirty && mbf.invalid">לא הוזן מספר</span>            
    </div>
    <div class="slider">
        <mat-slide-toggle [formControl]="autoRenew" (change)="onChange()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;מכפיל {{addonPrint}}</mat-slide-toggle>
    </div>
    <div>
        <p class="cbm">תוצאה בקו"ב:</p>
        <p class="result">{{cbm}}</p>
    </div>

</form>  
</div>

}


0 commentaires

3 Réponses :


2
votes

Raison de ne pas fonctionner: -

Vous avez mis votre événement de touche enfoncée uniquement sur le formulaire afin qu'il ne se déclenche que si vous appuyez sur la touche dans votre formulaire.

Solution:-

Utilisez - @HostListner comme suit dans votre classe dactylographiée:

  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) { 
    this.key = event.key;
    // Here you will get key
    this.keyDownFunction(event)        // Now you can call you function 
  }

J'espère que cela aidera


0 commentaires

1
votes

Importez HostListener dans votre fichier ts

importez {HostListener} depuis '@ angular / core';

Utilisez keydown au lieu de keypress

@HostListener('document:keydown', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
    if(event.key === 'F2'){
      console.log('F2 pressed');
      // Call Function
    } else if (event.key === 'Enter' && !isNaN(this.mbfValue)){
      this.cbm = this.mathService.mbf2cbm(this.mbfValue, this.autoRenew.value).toFixed(3);
    }
  }


0 commentaires

0
votes

Wow les gars qui ont parfaitement fonctionné. Et merci de m'avoir suggéré d'utiliser keydown au lieu de keypress - Pour ce faire, il est important de supprimer le (keydown) = "handleKeyboardEvent ($ event)" du code html sinon il affichera des messages doubles sur la console.

Merci beaucoup!


0 commentaires