我正在使用Ionic 5.0,并且有一个离子选择字段。我需要根据所选选项更改字段的背景。
我已经尝试了几件事。我目前在以下代码中的尝试是在ion-select中插入[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)
<ion-select [(ngModel)]="selectedVal" class="square" interface="popover" [ngStyle]="SetBackground(item.id)">
<ion-select-option *ngFor="let item of data" [value]="item.id" >
您的SetBackground函数在循环之前被调用。因此,没有item.id的参考。
你可以这样。
html
<select [ngStyle]="styleObj" (change)="SetBackground($event)">
<option *ngFor="let item of data" value={{item.id}}>
{{ item.name }}
</option>
</select>
ts
data = [
{
id: "transparent", name: ""
},
{
id: "green", name: "Forest"
},
{
id: "red", name: "Village"
},
{
id: "yellow", name: "Field"
},
{
id: "blue", name: "Water"
},
{
id: "purple", name: "Monster"
},
];
styleObj = {};
SetBackground(e) {
this.styleObj = {
'background-color': e.target.value,
};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句