将ngfor值传递给图像

时间:2019-06-10 05:57:33

标签: angular dart ngfor

我的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>

任何人都可以帮助我。

2 个答案:

答案 0 :(得分:1)

在您的this.$router.push('/about')方法中,将组件中的所选国家/地区设置为

selectCountry

然后将图像标签更改为

selectedCountry:any

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

Working demo

答案 1 :(得分:1)

您可以将整个国家对象与ngModel绑定,这不需要您手动遍历循环以获取选定的国家对象。双向绑定具有强大的功能。

<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>