如何更改 TS-File 中的样式?

How can I change the style in TS-File?

我写了一个定义了不同颜色的服务。现在我想为我的专栏设置不同的背景。使用 <th> 标签是不可能的,因为两列立即获得相同的颜色。

我的代码:

更改颜色服务

export class ChangeColorService {

  public defaultStyles = {
    firstDesignBackgroundColor: '#25a1b1',
    secondDesignBackgroundColor: '#c3c0c0',
  };

  sharedStyleSource = new ReplaySubject<any>(1);
  public sharedStyle = this.sharedStyleSource.asObservable();

  constructor() { }

  newStyle(obj: any) {
    this.defaultStyles[obj.name] = obj.value;
    console.log('defaultStyles:', this.defaultStyles);
    this.sharedStyleSource.next(obj);
  }
}

我的组件

  public myArray = [
    { attribute: 'firstColumn', name: 'Firstname'},
    { attribute: 'secondColumn', name: 'Lastname'},
  ];

ngAfterViewInit() {
    changeFirst('firstColumn');
    changeFirst('secondColumn');
  }

public changeFirst(attributeToChange: any) {
    const displayedColumn = this.displayedColumns.find((dc) => dc.attribute === attributeToChange);
    if (displayedColumn && displayedColumn !== null) {
      displayedColumn.attribute = this.changeColorService.defaultStyles.firstDesignBackgroundColor;
    }
  }

public changeSecond(attributeToChange: any) {
    const displayedColumn = this.displayedColumns.find((dc) => dc.attribute === attributeToChange);
    if (displayedColumn && displayedColumn !== null) {
      displayedColumn.attribute = this.changeColorService.defaultStyles.secondDesignBackgroundColor;
    }
  }

好像不是这样的。你能告诉我如何解决这个问题吗?

我有一个解决方案,但你们的服务没有!

我创建了一个带有参数的方法 changeColor()。该参数是 tables-output 的索引(在我的示例中,是字母数组中的索引)。所以方法changeColor() 检查索引,如果 indexeven (return color-one) 或 odd (return color-two) 每次都改变颜色。

颜色可以在.ts文件中设置。

public changeColor(index: number): string {
  if (index % 2 == 0 ) { // if is even
    return "#25a1b1"; // first color
  } else if (index % 2 == 1 ) { // if is odd
    return "#c3c0c0"; // second color
  } 
}

HTML-file 中的 background-color 我定义如下并在 background-color-CSS 属性之后设置方法 changeColor() 其中 return 两种颜色之一:

<tr *ngFor="let element of alphabet; index as i">
    <td style="background-color:{{ changeColor(i) }};"> {{ element.name }} </td>
</tr>

看看我的stackblitz