typescript - 为什么我不能从 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";
}
}
如您所见,表上是否没有选择(此处未放置逻辑),或者是否未选择当前行我想设置样式,否则我想要特定的行。
解决方案
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' };
}
推荐阅读
- django - Webclient 上 Session 的日志输出
- google-bigquery - 从 Google Data Studio 调用 Bigquery 存储过程
- jupyter-notebook - 如何在 Vader 情绪分析中添加我们自己的句子和极性
- strongloop - Loopback4 中包含记录的限制
- typescript - 如何在 TypeScript 中将多个类合二为一?
- flutter - Flutter 中的 SVG 图像路径错误“需要非负浮点值”
- javascript - 是否可以向影子根中的元素添加属性?
- java - 了解和配置字符串响应的 Spring JSON 编组配置
- python - 从 T5Tokenizer 导入 t5-base 失败
- 3d - 如何从两个输入变量进行插值以获得三个独立于变量的输出?我有22组实验数据