簡體   English   中英

Angular 5綁定到數組中的特定項目

[英]Angular 5 binding to a specific item in an array

我有一個以Angular模板驅動形式的國家/地區

"countries" : [  
   {  
      "id":1,
      "code":"NL"
   },
   {  
      "id":2,
      "code":"US"
   }
]

我在模型中有一個選定的ID:2

我想將值“ US”綁定到div中。 像這樣:

<div>{{countries[id==model.countryId].code}}</div>

角度5可能嗎? 我在網上看到數組的過濾器管道不再存在於角度中。

我讓它像這樣工作,但這不是很好,我會說:

<ng-container *ngFor="let country of countries">
   <div *ngIf="country.id==parentModel.countryId">{{country.code}}</div>
</ng-container>

您可以在打字稿中創建一個getter屬性,並像這樣使用它:

TS:

get CountryCode() {
    let country = this.countries.find(x=>x.id == this.parentModel.countryId);
    return country && country.code;
}

HTML

<div>{{ CountryCode }}</div>

ngx-pipeshttps://github.com/danrevah/ngx-pipes )有一些有趣的管道,例如filterBy ,您可以使用這種方式:

{{ countries | filterBy: ['id']: yourID }}

這將返回您指定ID的國家/地區。 它還有適合各種情況的管道

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM