我正在基于《星球大战》 API构建这个小型应用程序。我已经渲染了一些字符名称,所选的字符名称为我们提供了其他信息,例如头发颜色等。问题是我想将本地图像绑定到所选的那些字符。例如,如果我单击名称Luke SkyWalker,则Ill会了解他的特征,但是我也希望加载他的本地图像。我该如何实现?到目前为止的代码:
HTML:
<div class="container" *ngIf="people">
<ul *ngFor="let star of people.results">
<li (click)="onSelect(star)" [class.selected]="star === selectedPeople">{{star.name}}</li>
</ul>
<div class="row">
<div class="col-md-3">
<p>Height</p>
</div>
<div class="col-md-3">
<p>Hair Color</p>
</div>
<div class="col-md-3">
<p>Mass</p>
</div>
<div class="col-md-3">
<p>Eye Color</p>
</div>
</div>
<div class="row" *ngIf="selectedPeople">
<div class="col-md-3">
<input class="form-control" [(ngModel)]="selectedPeople.height">
</div>
<div class="col-md-3">
<input class="form-control" [(ngModel)]="selectedPeople.hair_color">
</div>
<div class="col-md-3">
<input class="form-control" [(ngModel)]="selectedPeople.mass">
</div>
<div class="col-md-3">
<input class="form-control" [(ngModel)]="selectedPeople.eye_color">
</div>
</div>
<!--PICTURE-->
<div class="col" *ngIf="picture">
<img class="img-fluid" [src]="luke"> ->This pic is harcoded
</div>
</div>
TS:
people: People;
selectedPeople: People;
picture=false;
luke: string ='../../assets/luke.jpg'
constructor(private starService: StarService) {
this.getChars();
}
ngOnInit() {
}
onSelect(persona: People): void {
this.selectedPeople = persona;
this.picture=true;
}
getChars() {
this.starService.getChars().subscribe(data => {
this.people = data;
console.log(this.people)
});
}
}
答案 0 :(得分:2)
如果您在资产目录中命名文件以匹配字符名称。例如,如果返回的JSON名称为Luke Skywalker
,则将图像文件命名为Luke Skywalker.jpg
。
然后,您可以在组件文件中创建如下函数:
getImageUrl(person) {
return "../../assets/" + person.name + ".jpg";
}
在您的HTML中,您可以
<img [src]="getImageUrl(selectedPeople)" />