Setting attributes for elements in NativeScript/Angular can be accomplished by utilizing item properties

Is it possible to call a function on an item element inside an ngFor loop in order to set some properties? Otherwise, I find myself having to loop twice - once in the script and then again in the template - setting temporary properties to a model that should only have specific ones. This results in ugly and redundant code, so I want to outsource the property-setting into a function.

Here's an 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 along those lines, but more complex in reality ;-)

Thank you in advance!

Answer №1

Here is the solution you've been looking for

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

--UPDATE--

To showcase a multi switch scenario, I have included an example which can be extended as needed.

Answer №2

The desired outcome can be obtained through the utilization of the onItemLoading event. In all honesty, it functions in a similar manner to manually looping over the items during the onInit stage. However, the advantage lies in the fact that the use of the onItemLoading event provides an inherent method to achieve this objective.

http://www.example.com/customizing-listview-items

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Electron is capable of downloading files just like any other standard web browser

I am currently working on an Ionic progressive web app that is integrated with Electron. I have used the <a href="http://myexternalserver.com/example.pdf" download> attribute to allow users to download a file. Surprisingly, in the browser, the file d ...

What is the best way to set a specific image as the initial image when loading 'SpriteSpin'?

I'm currently working on creating a 360-degree view using the SpriteSpin API. Everything is functioning as expected, but I have an additional request. I need to specify a specific image to be the initial landing image when the page loads. The landing ...

Provider in Angular2 that relies on multiple other Providers

Within my Angular2 application, I have various modules that offer Services and Configuration. Now, I want to integrate the @ngrx/store, which gathers reducers from all my modules. Below is the bootstrap code snippet: import {OpaqueToken} from 'angu ...

Building an anchor tag that employs the HTTP DELETE method within an Express.js app

Recently, I delved into using express.js with handlebars.js as my template engine. One task I wanted to tackle was creating a delete link that followed RESTful principles and used the HTTP DELETE verb instead of GET. After some trial and error, I discover ...

Updating partials with Ajax calls and displaying the updated content in a Rails application

Instead of using erb, I am using haml. So my code looks something like this: $("<%= escape_javascript(render @user) %>").appendTo("#users"); Unfortunately, the code mentioned in is not working for me. Any suggestions or ideas on how to make it w ...

What is the best way to transform a series of character codes into a string using JavaScript?

Check out this interesting function I came across: function ungarble(garble){ var s = ""; for( var i = 0; i < garble.length; i++ ) { s += String.fromCharCode(garble[i]); } return s; } This function accepts an array of charCodes as input an ...

Angular2's customer filter pipe allows for easy sorting and filtering of

Check out the component view below: <h2>Topic listing</h2> <form id="filter"> <label>Filter topics by name:</label> <input type="text" [(ngModel)]="term"> </form> <ul id="topic-listing"> <li *ngFo ...

Developing mongoose models using TypeScript for subdocuments

Exploring the integration of mongoose models with typescript, following a guide available at: https://github.com/Appsilon/styleguide/wiki/mongoose-typescript-models. Unsure how arrays of subdocuments align with this setup. For instance, consider the model ...

"I'm trying to incorporate react-datepicker into my ReScript application, but I'm struggling to

I am attempting to incorporate an external library like react-datepicker into my project. Below is the code snippet and how I am using it: module DatePicker = { @react.component @module("react-datepicker") external make: () => React.eleme ...

Enhance Your Search Bar with Ajax and JQuery for Dynamic Content Updates

My goal is to create a search bar that dynamically loads content, but I want the actual loading of content to start only after the user has finished typing. I attempted a version of this, but it doesn't work because it doesn't take into account ...

Variables in Angular DI become undefined when a method is called through a passed function reference

Utilizing Angular, I have a class with several Dependency Injection (DI) variables. During normal execution of a method within the class, everything functions as expected and I can access the injected instances of the DI variables. Now, my goal is to crea ...

Upon loading, the IntersectionObserver immediately declares the isIntersecting property true for all elements

Yesterday, when I executed this code, everything functioned as expected. The observer successfully loaded the images once they intersected the viewport: <template> <div id="gallery" class="gallery"> <div class=" ...

Refreshing GIF images in React using forceReload

In order to restart the gif animation every 12 seconds or whenever the activeIndex changes, I need to reload a GIF image with CHECKMARK_ANIMATION_ICON as the source. Below is the code: const reloadImgSource = (imgSource) => { setTimeout(() =& ...

The cdkConnectedOverlayScrollStrategy does not function as expected within an ng-template

I have implemented ng-template with cdk to generate an overlay. I am looking for a way to automatically update the position of this cdk's overlay when the cdkOverlayOrigin changes. I have tried using cdkConnectedOverlayScrollStrategy, but it is not w ...

Finding the specific index of an element in the code has proven challenging, as it consistently returns a value of -1

const index = this.List.findIndex((item:any) => { return item.NAME === result.NAME; }); The index is consistently returning -1 even when the element is found in the List. ...

Module for importing text without verifying types using wildcards

Here is a unique module definition using the wildcard character: declare module 'custom!*' { const data: string; export default data; } Check out how it's imported: import * as myData from 'custom!./myCustomData.txt'; B ...

What's the best approach for implementing TimeInput exclusively in React-Admin?

I discovered this helpful code snippet on the React-Admin documentation that allows me to input both a date and time: import { DateTimeInput } from 'react-admin'; <DateTimeInput source="published_at" /> But now I'm wonderin ...

Exploring the Contrast between Cursor and Stream in Node.js

When it comes to extracting large data from a database, there are options like using stream or cursor. I'm curious to find out which option is more efficient and also dive into how cursor and stream work internally in node js. ...

Server-side Data Fetching with Nuxt.js

Is there a method to exclusively retrieve data from an API on the server-side in NuxtJS due to me needing to include my API_TOKEN in the request headers? Sample Code: <template> <div> <h1>Data obtained using asyncData</h1> ...

Thymeleaf: Expression parsing error

I am working on a Thymeleaf template that includes pagination functionality. <ul class="results_perpage" > <li th:if="${previous != null}"><a th:href="javascript:movePage(`${previous}`);" class="results_menu" th:text="PREVIOUS">< ...