首页 > 解决方案 > 为什么我不能从 Typescript 中的方法动态设置样式

问题描述

我正在尝试使用.ts文件中的方法设置表中的行样式,但出现以下错误:

> IndexComponent.html:16 ERROR Error: Cannot find a differ supporting
> object 'cursor:pointer'
>     at KeyValueDiffers.push../node_modules/@angular/core/fesm5/core.js.KeyValueDiffers.find
> (core.js:16533)
>     at NgStyle.set [as ngStyle] (common.js:3816)
>     at updateProp (core.js:18743)
>     at checkAndUpdateDirectiveInline (core.js:18494)
>     at checkAndUpdateNodeInline (core.js:19801)
>     at checkAndUpdateNode (core.js:19763)
>     at debugCheckAndUpdateNode (core.js:20397)
>     at debugCheckDirectivesFn (core.js:20357)
>     at Object.eval [as updateDirectives] (IndexComponent.html:16)
>     at Object.debugUpdateDirectives [as updateDirectives] (core.js:20349)

HTML

<table class="table">
      <tr>
        <th>Id</th>
        <th>Name</th>
      </tr>

      <tr [ngStyle]="setStyle(item)" (mousedown)="onSelectionChanged(item)" *ngFor="let item of viewComputers">
        <td>{{item.id}}</td>
        <td>{{item.username}}</td>
      </tr>
    </table>

TS

export class IndexComponent implements OnInit {

  public viewComputers:Computer[]=null;
  protected SelectedComputer:Computer=null;

  onSelectionChanged(data:Computer){
    this.SelectedComputer=data;
  }

  public setStyle(value:Computer):string{

    var style="cursor:pointer";
    if(this.SelectedComputer==null ||!(this.SelectedComputer.id==value.id) ){
      console.log(style);
      return style;
    }
    return style+";background-color: #6699ff";
  }

}

如您所见,表上是否没有选择(此处未放置逻辑),或者是否未选择当前行我想设置样式,否则我想要特定的行。

标签: typescriptbindingstyles

解决方案


ngStyle 需要对象但不是字符串https://angular.io/api/common/NgStyle

@Input()
ngStyle: { [klass: string]: any; }

代码更改

  public setStyle(value:Computer):any{

    let style: any ={'cursor': 'pointer'};
    if(this.SelectedComputer==null ||!(this.SelectedComputer.id==value.id) ){
      console.log(style);
      return style;
    }
    return {...style, 'background-color' : '#6699ff' };
  }

推荐阅读