javascriptangulartypescriptangular2-nativescript

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


Solution

  • It could be achieved either more or less by using onItemLoading event. 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.

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