将 ngfor 值传递给图像

Pass ngfor value to the image

我的 JSON 字符串值如下所示,我正在将国家名称加载到 Select 控件。这工作正常,现在无论何时选择一个国家,相关图像都应该传递给 IMG 标签示例,如果选择国家印度,那么图像应该是这样的

<img src="india.png">

如果选择英格兰,则图像标签应

<img src="hello.png"> 

下面是我从 Web 服务调用中获得的 JSON 值。

[{
"Name": "England ",
"ImageFile": hello.png,
"Id": 1
},
{
"Name": "South Africa",
"ImageFile": test.png,
"Id": 2
}, 
{
"Name": "India",
"ImageFile": india.png,
"Id": 2
}]

我在 Dart 中编写了获取国家 ID 的函数,该值在 dart 函数中是正确的。现在我需要根据所选国家/地区更改图像值

   <label style="alignment: center" for="countries">Country
        <select class="form-control" id="countries" *ngIf="sCountries.length > 0" [ngModel]="0" (ngModelChange)="selectCountry($event)">
            <option value="0">All</option>
            <option *ngFor="let country of sCountries" value="{{country['Id']}}">{{country['Name']}}</option>
        </select>
    </label>

谁能帮帮我。

在您的 selectCountry 方法中,在您的组件中设置选定的国家/地区,例如

selectedCountry:any

selectCountry(countryId){
var country=this.sCountries.find(c=>c.Id==countryId)
this.selectedCountry=country;
}

然后将图像标签更改为

<img [src]="selectedCountry?.ImageFile">

Working demo

您可以将整个国家/地区对象与 ngModel 绑定,这将不需要您手动迭代循环来获取选定的国家/地区对象。 Two-way绑定的力量很大。

<label style="alignment: center" for="countries">Country
    <select class="form-control" id="countries" *ngIf="sCountries.length > 0" [(ngModel)]="selectedCountry">
        <option *ngFor="let country of sCountries" [value]="country">{{country['Name']}}</option>
    </select>
</label>

<ng-container *ngIf="selectedCountry"> 
    <img [src]="selectedCountry.ImageFile">
</ng-container>