简体   繁体   English

根据 nativescript/angular 中的项目属性设置元素属性

[英]Set element attributes based on item properties in nativescript/angular

Currently, I wonder if it is possible inside ngFor loop to call a function on an item element to set some properties.目前,我想知道是否可以在ngFor循环中调用 item 元素上的函数来设置一些属性。 Otherwise, I would have to loop twice (first in the script part and second in the template part) and set just temporary properties to a model which should only have specific ones, but the code to set the property makes the template ungly and is redundant so I want to outsource it into a function.否则,我将不得不循环两次(第一次在脚本部分,第二次在模板部分)并将临时属性设置为应该只有特定属性的模型,但是设置属性的代码使模板变得丑陋且多余所以我想把它外包成一个函数。

For example:例如:

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

and

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;
}

Something like that, but of course in the flesh more complex ;-)类似的东西,但当然在肉体中更复杂;-)

Thanks in advance!提前致谢!

This should be what youre after这应该是你所追求的

<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>

--EDIT-- - 编辑 -

I added a multi switch as an example, you can make the multi as long as possible我添加了一个多路开关作为例子,你可以让多路尽可能长

It could be achieved either more or less by using onItemLoading event.它可以通过使用onItemLoading事件或多或少地实现。 To be honest, it acts quite similar as if you would loop over the items onInit , but the benefit is, that the onItemLoading event is a build-in way to achieve that aim.老实说,它的行为与您循环onInit项目非常相似,但好处是onItemLoading事件是实现该目标的内置方式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM