我在ngFor中有一个选择下拉列表。如何在循环中检索每个选择的值?
此外,我想根据每个选择的值更改p标记内每个句子的颜色。我该怎么办?
图片:https://i.stack.imgur.com/V33Cl.png
每个句子应具有颜色,具体取决于在其旁边的下拉列表中选择的值。而且更改需要立即进行。
此处的代码不起作用。
<div *ngIf="sentences?.length > 0;else noItems">
<ul *ngFor="let sentence of sentences;let i = index;" class="collection">
<li class="collection-item">
<p>{{sentence.data}} </p>
<p style="margin-left:20px; font-size:12px!important">
<select (change)="filterChanged(selected[i])">
<option *ngFor="let cat of foods" [value]="cat.value">
{{cat.viewValue}}
</option>
</select>
</p>
</li>
ts文件:
filterChanged(selectedValue:string ){
this.printedOption = selectedValue;
console.log("COLOR",this.printedOption );
if(this.printedOption=='1'){
this.color="pink";
}
if(this.printedOption=='2'){
this.color="red";
}
}
答案 0 :(得分:3)
尝试一下:
<select #select (change)="filterChanged(select.value, sentence.data)">
,并且要更改 P 标签的颜色,必须定义一个全局对象,并在filterChanged()函数中为该对象设置一个键:
public colorObj = {};
filterChanged(selectedValue:string, key) {
let colors = {1: 'red', 2: 'green'};
this.colorObj[key] = colors[selectedValue];
}
并在HTML中使用ngStyle
设置颜色:
<p [ngStyle]="{'color': colorObj[sentence.data]}">
答案 1 :(得分:2)
您可以在多个条件下使用[ngClass]
来应用CSS类
HTML代码:
<div>
<ul *ngFor="let sentence of sentences;let i = index;" class="collection">
<li class="collection-item">
<p [ngClass]="{'red': sentence?.disco == 1 , 'green': sentence?.disco == 2 }">{{sentence.viewValue}} </p>
<p style="margin-left:20px; font-size:12px!important">
<select #val (change)="onChange(val.value,i)">
<option *ngFor="let cat of foods" [value]="cat.value" >
{{cat.viewValue}}
</option>
</select>
</p>
</li>
</ul>
</div>
CSS:
.red{
background-color: red;
}
.green{
background-color: green;
}
TS代码:
import { Component } from '@angular/core';
/**
* @title Basic select
*/
@Component({
selector: 'select-overview-example',
templateUrl: 'select-overview-example.html',
styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
foods: any[] = [
{ value: '1', viewValue: 'Pizza' },
{ value: '2', viewValue: 'Tacos' }
];
sentences: any[] = [
{ value: 'steak-0', viewValue: 'Steak' },
{ value: 'pizza-1', viewValue: 'Pizza' },
{ value: 'tacos-2', viewValue: 'Tacos' }
];
onChange(selectedValue, index) {
console.log(selectedValue)
this.sentences[index].disco = selectedValue;
}
}