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()"> ××פ×× {{addonPrint}}</mat-slide-toggle>
</div>
<div>
<p class="cbm">ת×צ×× ××§×"×:</p>
<p class="result">{{cbm}}</p>
</div>
</form>
</div>
}
3 Réponses :
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
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);
}
}
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!