You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 2+下基于JSON实现货币代码输入匹配查询的技术咨询

Angular 2+ 实现简易货币代码键值查询功能

咱直接整个轻量版的实现,完全不用那些复杂的第三方组件,刚好匹配你要的「输入2/3位货币代码,实时返回对应名称」的需求,步骤超清晰:

第一步:准备货币映射数据

你可以把货币代码的JSON存在项目的assets文件夹里(比如命名为currency-mapping.json),内容就用你给的示例:

{
  "42": "42 Coin",
  "365": "365Coin",
  "404": "404Coin",
  "611": "SixEleven",
  "808": "808",
  "BTC": "Bitcoin",
  "ETH": "Ethereum"
}

当然也可以直接在组件里定义这个对象,省得读文件,看你需求选就行。

第二步:组件逻辑实现

在你的Angular组件(比如currency-search.component.ts)里,实现输入监听和查询逻辑:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-currency-search',
  templateUrl: './currency-search.component.html',
  styleUrls: ['./currency-search.component.css']
})
export class CurrencySearchComponent implements OnInit {
  currencyMapping: { [key: string]: string } = {};
  userInput: string = '';
  matchedCurrencyName: string | null = null;

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // 从assets加载JSON数据,如果是直接定义对象就跳过这步
    this.http.get<{ [key: string]: string }>('assets/currency-mapping.json')
      .subscribe(data => {
        this.currencyMapping = data;
      });
  }

  onInputChange(): void {
    // 先把输入转成大写(适配货币代码的常规格式,也可以改成不区分大小写匹配)
    const inputKey = this.userInput.trim().toUpperCase();
    // 仅当输入长度为2或3位,且在映射表中存在时返回结果
    if ((inputKey.length === 2 || inputKey.length === 3) && this.currencyMapping[inputKey]) {
      this.matchedCurrencyName = this.currencyMapping[inputKey];
    } else {
      this.matchedCurrencyName = null; // 不匹配就清空结果
    }
  }
}

第三步:模板页面编写

在对应的HTML模板里,放输入框和结果展示区域,逻辑超直观:

<div class="currency-search-container">
  <label for="currency-code">输入货币代码:</label>
  <input 
    type="text" 
    id="currency-code" 
    [(ngModel)]="userInput"
    (input)="onInputChange()"
    placeholder="比如BTC、42"
  >
  <!-- 匹配到结果就显示 -->
  <span *ngIf="matchedCurrencyName" class="result">
    对应名称:{{ matchedCurrencyName }}
  </span>
  <!-- 输入后无匹配的提示 -->
  <span *ngIf="userInput && !matchedCurrencyName" class="no-result">
    未找到对应货币
  </span>
</div>

额外优化小Tips

  • 可以加个简单的CSS样式,把结果和输入框对齐,视觉上更舒服;
  • 如果要支持模糊匹配(比如输入BT就显示Bitcoin),可以把onInputChange里的逻辑改成遍历映射对象的键,用includes判断;
  • 要是需要兼容更多输入场景,比如允许小写输入,已经在代码里做了转大写处理,也可以改成不区分大小写的匹配逻辑。

这个实现完全是轻量定制的,没有多余的复杂逻辑,刚好满足你的需求~

内容的提问来源于stack exchange,提问作者oudekaas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:10:08