如何在select元素中选择更改单元格颜色?

时间:2018-05-16 09:41:29

标签: angular

我尝试根据下拉菜单中选择的值更改表格中的某些单元格,下拉列表中的这些值会随机分配到表格的单元格内。

每个单元格值都有一个指定的类,它等于单元格中的值。我想要它,以便在下拉列表中选择值时,将相关的单元格与更改颜色的值相关联。到目前为止,我有:

app.coponent.html:

<div style="text-align: center">
<app-inputs (event)="getDataFromChild($event)"></app-inputs>
<p></p>
({{ colVal }}) cols and ({{ rowVal }}) rows
<p></p>
<select [(ngModel)]=val (ngModelChange)="value()">
    <option value="One">One</option>
    <option value="Two">Two</option>
    <option value=" Three">Three</option>
    <option value="Four">Four</option>
    <option value="Five">Five</option>
</select>
<p></p>

<table style="border: 1px solid black;">
    <thead>
        <tr style="border: 1px solid black;" *ngFor="let row of tableData">

            <td style="border: 1px solid black;" *ngFor="let column of row" class="{{ column }}">
                {{ column | uppercase }}
            </td>
        </tr>
    </thead>
</table>

app.component.ts:

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NgModel } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
 })
export class AppComponent {
   colVal: number;
   rowVal: number;
   randStr: string;
   randVal: any[] = [];
   tableData: any[] = [];
   randArr: any[] = ['One', 'Two', 'Three', 'Four', 'Five'];
   val: string;

getDataFromChild(data) {
  this.colVal = data.columns;
  this.rowVal = data.rows;
  this.getRnd();
}

  getDataFromChildTwo(data) {
    this.randVal = data;
    console.log(this.randVal);
}

  getRnd() {
    this.tableData = [];
    for (let i = 0; i < this.rowVal; i++) {

      const values = [];
      for (let j = 0; j < this.colVal; j++) {
        const randNo = Math.floor(Math.random() * 4);
        const storedVal = this.randArr[randNo];
        values.push(storedVal);
    }
    this.tableData.push(values);
    console.log(this.tableData);
  }
}
    value() {
     console.log(this.val);
   }
}

tl; dr - 我想在下拉列表中更改包含所选选项的单元格的颜色,此刻我有点迷失了!

1 个答案:

答案 0 :(得分:0)

模板:

<td style="border: 1px solid black;" 
    *ngFor="let column of row" 
    class="{{column}}" 
    [ngClass]="{'selected': column == val }">
        {{ column | uppercase }}
</td>

和css:

td.selected {
  background-color: red;
}

修改

@ClutchBleu回答您的评论:column == vall使用column val值是否等于<select>值绑定到[(ngModel)] >