为什么我的 Angular 代码没有显示正确的输出?

问题描述 投票:0回答:1

我的任务是输入电子邮件地址并检查每个字符,如果该字符是希伯来语 - 将其转换为英语 代码的问题是它无法正确转换,我在输入字段中写入了以下文本:“r0556”,它应该显示“r0556”,而不是显示各种双精度和长字符,如您在图片

这是html页面的代码片段

<h1>נא הכנס כתובת מייל</h1>
<input (keyup)="getLetter($event)" (mouseover)="onComment()" (mouseleave)="offComment()" 
type="text">
<div id="comment">{{comment}}</div>
<button type="button" (click)="clickButton()">{{button}}</button>

这是 TypeScript 页面的代码片段

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-email-adress',
  standalone: true,
  imports: [FormsModule],
  templateUrl: './email-adress.component.html',
  styleUrl: './email-adress.component.css'
})
export class emailAddressComponent {
  comment = "";
  onComment() {
    this.comment = "חובה למלא כתובת מייל"
  }
  offComment() {
    this.comment = "";
  }

  HebrewLetters = ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק', 'ר', 'ש', 'ת'];
  EnglishLetters = ['t', 'c', 'd', 's', 'v', 'u', 'z', 'j', 'y', 'h', 'f', 'k', 'n', 'b', 'x', 'g', 'p', 'm', 'e', 'r', 'a', ','];
  emailAddress = "";

  getLetter(eventLetter: any) {
    let inputLetter = eventLetter.target.value;
    let index = this.HebrewLetters.indexOf(inputLetter);

    if (index !== -1) {
      this.emailAddress += this.EnglishLetters[index];
    } else {
      this.emailAddress += inputLetter;
    }

    if (eventLetter.keyCode === 13) {
      eventLetter.target.value = this.emailAddress;
      alert("This email address: " + this.emailAddress);
      this.emailAddress = "";
    }
  }

  button = "@gmail.com";
  clickButton() {
    this.emailAddress += this.button;
    alert("כתובת המייל שנקלטה היא: " + this.emailAddress)
  }

}

在此输入图像描述 在此输入图片描述

angular angularjs events angularjs-directive
1个回答
0
投票

问题在于你的逻辑:它设置为检查单个键,但你检查整个输入值,将其与局部变量连接起来,然后导致所描述的重复行为,并且两个变量不同......

所以,你可以监听关键代码(

eventLetter.key
),但是,对于剪切复制粘贴等来说,它不会有效

为了安全起见,为什么不检查并替换输入值中的所有字符,并将其与本地

emailAddress
结合起来,因为现在它们被拆分,并且会有所不同。

尝试这段代码(注释中的说明),您可以根据您的用例重构它:

  getLetter(eventLetter: KeyboardEvent) {

    // get input value
    let value = (eventLetter.target as HTMLInputElement).value;

    // get unique cahrs
    const chars = [...new Set(value.split(''))];

    // check and replace all chars, mutate input
    chars.forEach(char=>{
      
      let index = this.HebrewLetters.indexOf(char);
      //console.log('ide', char, index, this.EnglishLetters[index])
      if (index !== -1) {
        value = value.replaceAll(char, this.EnglishLetters[index])
      }
    });

    // connect with email address
    this.emailAddress = value;
    

    if (+eventLetter.code === 13) {
      alert("This email address: " + this.emailAddress);
      this.emailAddress = value = "";
      //value = this.emailAddress;
    }    

    console.log('emailAddress', this.emailAddress);

    
  }
© www.soinside.com 2019 - 2024. All rights reserved.