我使用的是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)
<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,
};
}
呜呜!它有效!非常感谢阿伦!
这是最后一个HTML代码,其中包含了离子材料。。。
<ion-select [(ngModel)]="selectedVal" [ngStyle]="styleObj" (ionChange)="SetBackground($event)" class="square" interface="popover">
<ion-select-option *ngFor="let item of data" [value]="item.id" >
{{ item.name }}
</ion-select-option>
</ion-select>
还有…
styleObj = {};
SetBackground(bg) {
this.styleObj = {
'background-color': bg.target.value,
};
}
再次感谢!
ps。下面是下一步。。。
我希望屏幕上有一个11x11的select语句网格,每个语句都有独立的颜色。你会怎么做?