html - vreau să declanșez o funcție când facem clic pe o tastă specifică?
Vom declanșa o funcție pe baza valorilor codului caracterelor tastelor.
Iată exemplul pentru a obține valorile codului caracterelor tastelor
window:keypress este un eveniment JavaScript. Acest eveniment este declanșat în întreaga fereastră
<div>
<p (window:keypress)="getcharcodeValue($event)">Click me!</p>
</div>
<p*ngIf="show">show me</p>
De exemplu, vrem să declanșăm funcția getcharcodeValue() pentru tasta Enter. Codul tastei pentru Enter este 13. Acum, în întreaga fereastră, când apăsăm tasta Enter, funcția se va declanșa. Inițial, setăm valoarea lui show ca fiind true.
triggerFunction(){
this.show = true
}
getcharcodeValue(event:any){
if(event.keyCode == 13){
triggerFunction()
}
Răspuns #1
Cauți un ascultător de gazdă, putem specifica direct evenimentul de care avem nevoie și doar să comutăm flagul
Cod complet
import { CommonModule } from '@angular/common';
import { Component, HostListener } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
<div>
<p>Click me!</p>
</div>
<p *ngIf="show">show this</p>
`,
})
export class App {
name = 'Angular';
show = false;
@HostListener('document:keydown.enter', ['$event']) onKeydownHandler(
event: KeyboardEvent
) {
this.show = true;
}
}
bootstrapApplication(App);
Demonstrație Stackblitz
