【发布时间】:2020-08-25 05:54:17
【问题描述】:
我使用的是 Ionic 5.0,并且我有一个离子选择字段。我需要根据所选选项更改字段的背景。
我已经尝试了几件事。我目前在下面的代码中的尝试是在离子选择中插入 [ngStyle]="SetBackground(item.id)" 但这不起作用。我也试过 [ngStyle]="SetBackground($event)"。我考虑过以某种方式将其添加到 (ionChange)="OnChange($event)" 但无法弄清楚如何做到这一点。似乎我只需要使用 item.id 来更改背景,但对于我来说,我就是想不通。
这是我的 HTML 代码。我希望这足以帮助我找到答案。
<ion-content>
<div id="game-board">
<ion-img class="map-img" src="../assets/img/map-a.png"></ion-img>
<ion-select [(ngModel)]="selectedVal" class="square" interface="popover" [ngStyle]="SetBackground(item.id)">
<ion-select-option *ngFor="let item of data" [value]="item.id" >
{{ item.name }}
</ion-select-option>
</ion-select>
</div>
</ion-content>
还有我的 ts
import { Component } from '@angular/core';
import { Platform } from '@ionic/angular';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
data: { id: string; name: string; }[];
constructor(private platform: Platform) {
this.platform.ready().then(() => {
this.data = [
{
id: "transparent", name: ""
},
{
id: "green", name: "Forest"
},
{
id: "red", name: "Village"
},
{
id: "yellow", name: "Field"
},
{
id: "blue", name: "Water"
},
{
id: "purple", name: "Monster"
},
]
})
}
SetBackground(bg) {
let newColor = {
'background-color': bg.target.value,
};
return newColor
}
我得到的错误...
HomePage.html:12 ERROR TypeError: Cannot read property 'id' of undefined
at Object.eval [as updateDirectives] (HomePage.html:14)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:45259)
at checkAndUpdateView (core.js:44271)
at callViewAction (core.js:44637)
at execComponentViewsAction (core.js:44565)
at checkAndUpdateView (core.js:44278)
at callViewAction (core.js:44637)
at execEmbeddedViewsAction (core.js:44594)
at checkAndUpdateView (core.js:44272)
at callViewAction (core.js:44637)
【问题讨论】:
标签: angular ionic4 ion-select