如何解决Angular 9 中搜索栏内容的交换进行了两次,但我只调用了一次
我正在尝试使用 Angular 9 构建货币转换器应用程序,其中数据来自外部 api。应用程序看起来像这样。
事情概述(与我面临的问题有关)
-
顶部的两个搜索栏从用户那里获取国家/地区名称。我使用 [(ngModel)] 对这些国家/地区值进行了双向绑定。我已将 ngbTypeAhed 用于这些搜索栏的预输入功能。
-
forex_details 变量具有 json objects() 数组,其中包含以下格式的国家/地区及其符号。使用来自这个文件的数据,我得到输入中提供的国家名称的符号
[{ "Entity": "INDIA","Currency": "Indian Rupee","AlphabeticCode": "INR","NumericCode": 356,"MinorUnit": 2,"WithdrawalDate": "" },.....]
-
一个外部 API (alpha vantage),我从中获取基于两个国家/地区名称符号的货币换算数据
实际问题
- 默认情况下,我将symbol_1 指定为“USD”,将symbol_2 指定为“INR”(国家/地区1 和国家/地区2 没有任何默认值)。当我点击交换按钮时,它给出了想要的结果。
- 但是,当我尝试输入新的国家/地区名称或为 country_1 和 country_2 提供默认值时,交换无法正常工作。 formatter1() 和 formatter2() 方法被调用两次,下面是控制台的屏幕截图。
我想交换这两个国家/地区名称(以及符号)并在这些搜索栏中反映相同的内容。请检查下面的代码并尽可能提供帮助。
.html 文件
<!--search bar for first country-->
<form class="me-3">
<input type="search" [(ngModel)]="country_1" name ="country_1"
class="form-control" placeholder="ENTER 1ST COUNTRY" aria-label="Search"
[ngbTypeahead]="search_country" [resultTemplate]="rt" [inputFormatter]="formatter1">
</form>
<!-- button for swapping -->
<button class="btn btn-rounded btn-warning shadow"
(click)="swapCountries(country_1,country_2)">
<i class="bi bi-arrow-left-right"></i>
</button>
<!--search bar for second country-->
<form class="me-3">
<input type="search" [(ngModel)]="country_2" name ="country_2"
class="form-control" placeholder="ENTER 2ND COUNTRY" aria-label="Search"
[ngbTypeahead]="search_country" [resultTemplate]="rt" [inputFormatter]="formatter2">
</form>
<!--for typeahead highlighting-->
<ng-template #rt let-r="result" let-t="term">
<ngb-highlight [result]="r.Name" [term]="t"></ngb-highlight>
</ng-template>
.ts 文件
//entity --> country name and alphabetic code --> country symbol for foreign exchange
// search_country variable is used for typeahead functionality
search_country: OperatorFunction<string,readonly {AlphabeticCode,Entity}[]> = (text$: Observable<string>) =>
text$.pipe(
debounceTime(200),map(term => term === '' ? []
: this.forex_details.filter(v => v.Entity.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0,5)))
//returns country_1 name to first search bar
formatter1 = (x: {Entity: string,AlphabeticCode: string}) => {
this.country_1 = x.Entity; //storing country and symbol name as per user input
this.symbol_1 = x.AlphabeticCode;
return x.Entity;
};
//returns country_2 name to first search bar
formatter2 = (x: {Entity: string,AlphabeticCode: string}) => {
this.country_2 = x.Entity; //storing country and symbol name as per user input
this.symbol_2 = x.AlphabeticCode;
return x.Entity;
};
swapCountries(country_1,country_2) {
let temp2 = this.symbol_1; //swapping symbols
this.symbol_1 = this.symbol_2;
this.symbol_2 = temp2;
this.country_2 = country_1 //swapping country names
this.country_1 = country_2
}
P.S:我删除了 console.log() 语句,因为它使代码变得冗长。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。