首页 > 解决方案 > Angular 6 使用 ngFor 中不同列的 Renderer2 更改样式

问题描述

我已经使用 ngFor 向表中添加了列。当用户单击<td>它时,它会打开一个对话框并返回一些值。根据选定的值,它<td>使用 Renderer2 更改特定的背景颜色。基于返回的值,我也想更改其他颜色的颜色<td>。返回值具有我想要进行更改item的 s 对象。<td>我怎样才能做到这一点?

<td 
   *ngFor="let item of items; index as i"
   (click)="openDialog(someVal)"
    #someVal
>

组件.ts

  openDialog(someVal): void {

      // Some Conditions .................

       this.rd.setStyle(someVar, 'background-color', this.colorCode);
    });
  }

标签: javascriptangulartypescript

解决方案


您可以使用 Directive :您可以定义自己的指令来将行为附加到 <td>DOM 中的元素。

<td [dialog]="someVal"
*ngFor="let item of items; index as i"
 >

班级

 import { fromEvent  } from 'rxjs';

 @Directive({
 selector: '[dialog]'
 })
 export class DialogDirective{

 public action: ElementRef ;

  constructor( elementRef: ElementRef<HTMLElement>) {
  this.action = elementRef ;
  }

 @Input() set dialog( someVal : any ) {

 // Some Conditions ...

 // Subscription
 fromEvent(this.action.nativeElement, 'click').pipe(
  .....

 }

推荐阅读