【问题标题】:Set element attributes based on item properties in nativescript/angular根据 nativescript/angular 中的项目属性设置元素属性
【发布时间】:2017-04-21 13:47:30
【问题描述】:

目前,我想知道是否可以在ngFor 循环中调用项目元素上的函数来设置一些属性。否则,我将不得不循环两次(第一次在脚本部分中,第二次在模板部分中)并将临时属性设置为应该只有特定属性的模型,但是设置属性的代码会使模板变得不美观并且是多余的所以我想把它外包给一个函数。

例如:

<StackLayout *ngFor="let item of items">
    <Label setProperties(el,item)></Label>
</StackLayout>

function setProperties(el,item) {
    el.text = item.fullname;
    let color = '';
    switch(item.state) {
        case 'success':
            let color = 'green';
            break;
        case 'fail':
            let color = 'red';
            break;
    }
    el.style.color = color;
}

类似的东西,但在肉体中当然更复杂;-)

提前致谢!

【问题讨论】:

  • 喜欢循环两次。从视图绑定调用函数通常是一个非常糟糕的主意。
  • 好的,只是出于兴趣,您能否简单地向我解释一下为什么这个想法会不好?
  • 我知道,但它是用于构建移动应用的 teleriks nativescript UI。
  • 因为每次更改检测运行时都会调用绑定中的方法,而且这种情况可能非常频繁。没有什么好方法可以在视图中完成您想要的。
  • 太糟糕了。不过谢谢你的解释。

标签: javascript angular typescript angular2-nativescript


【解决方案1】:

这应该是你所追求的

<StackLayout *ngFor="let item of items">
    <Label [style.color]="item.state == 'success' ? 'green' : item.state == 'failed' ? 'red' : item.state == 'other' ? 'yellow' : 'blue' " [text]="item.fullname"></Label>
</StackLayout>

--编辑--

我添加了一个multi开关作为例子,你可以把multi越长越好

【讨论】:

  • 当然是。在那种简单的情况下,我不会要求答案。但是示例只是一个示例,而不是整个真实的项目代码:D 想象一下,在 switch 或深层嵌套属性中会有大约十个案例......
  • 然后写一个多开关语句?
  • 您的意思是在属性中嵌套三元运算符?
  • 可能,但不是很好。
  • 那么使用函数呢?
【解决方案2】:

使用onItemLoading 事件或多或少都可以实现。老实说,它的行为非常类似于循环遍历项目 onInit,但好处是,onItemLoading 事件是实现该目标的内置方式。

http://docs.telerik.com/devtools/nativescript-ui/Controls/NativeScript/ListView/How-To/item-customization#the-itemloading-event

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2011-03-31
    • 1970-01-01
    相关资源
    最近更新 更多