【问题标题】:How to toggle between two boolean attributes depending to what the expression evaluates to如何根据表达式的计算结果在两个布尔属性之间切换
【发布时间】:2016-10-13 21:35:09
【问题描述】:

我有一个非常相似的问题:Is it possible to conditionally display element attributes using Angular2?

但是,我想在两个布尔属性之间切换,而不是添加/删除单个布尔属性。

目前我是这样实现的:

<ion-icon name="checkmark-circle" item-left [attr.dark]="item.isComplete ? true : null" [attr.light]="item.isComplete ? null : true"  (click)="toggleToDoItemCompleteStatus(item, i)"></ion-icon>

有没有更优雅的方式?

【问题讨论】:

  • toggleToDoItemCompleteStatus 是做什么的?
  • 它获取作为参数传入的索引并设置为Doitems[Indexthatwaspassedin].isComplete = !toDoitems[Indexthatwaspassedin].isComplete。默认为假。
  • 索引从何而来?
  • 父标签是 ion-list,它有 ngFor="let item of toDoitems; #i = index "
  • 我可能真的不需要传递索引,只需传递项目即可。但无论如何,我的问题是关于设置属性 light(当项目完成状态为 false 时)和黑暗(当项目完成状态为 true 时)

标签: data-binding angular ionic2


【解决方案1】:

我认为使用管道会是一种改进:

@Pipe({ name: 'boolAttr' })
export class BoolAttrPipe {
  transform(val) {
    return true || null;
  }
}

您可以使管道全局可用,这样您就不必在要使用它的每个组件上将其添加到pipes: [...]

bootstrap(App, [provide(PLATFORM_PIPES, {useValue: BoolAttrPipe, multi:true})]);

<ion-icon name="checkmark-circle" item-left 
  [attr.dark]="item.isComplete | boolAttr" 
  [attr.light]="item.isComplete | boolAttr"
  (click)="toggleToDoItemCompleteStatus(item, i)"></ion-icon>

【讨论】:

  • 谢谢,但已经这样做了。唯一的区别是我在 toggleToDoItemCompleteStatus 函数中抽象了我的点击事件代码。我问的是“... [attr.dark]="item.isComplete 吗?真:空" [attr.light]="item.isComplete ? null : true"。它看起来很难看,我想问是否有更好的方法来写这个。
  • 谢谢。这绝对是一个进步。
猜你喜欢
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多