This is a migrated thread and some comments may be shown as answers.

NativeScript: load ListView.itemTemplate from XML file

1 Answer 133 Views
General Discussion
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Marc
Top achievements
Rank 1
Marc asked on 19 Jan 2017, 12:25 PM

Hello,

in one of the pages in our NativeScript app I need to dynamically build the UI within JavaScript and that page contains a TabView with a variable count of TabEntries. In each Tab, there is one ListView and I want to use the same itemTemplate in each ListView.

 

When I build the UI in XML, I can include one template via namespace to multiple ListViews like that:

<!-- fixed template -->
<ListView items="{{ items}}">
    <ListView.itemTemplate>
        <StackLayout >
            <Label text="{{ name }}"/>
            <!-- ... -->
        </StackLayout>
    </ListView.itemTemplate>
</ListView>
<!-- using namespace  -->
<ListView items="{{ items}}">
    <ListView.itemTemplate>
        <myNameSpace:list-template/>
    </ListView.itemTemplate>
</ListView>

 

Right now, I assign the the itemTemplate to my ListView as a String:

listViewSubCategories.itemTemplate =
 `<StackLayout>
         <Label text="{{ name }}" />
</StackLayout>`;

 

but that's not the best solution. Is there another way to include this Template to my ListView?

I know Angular offers the opportunity to assign a templateURL or something like that, but we use NativeScript with Vanilla JavaScript.

 

I am thankful for any advice.

 

Best regards

 

 

 

 

1 Answer, 1 is accepted

Sort by
0
Nick Iliev
Telerik team
answered on 24 Jan 2017, 02:14 PM
Hi Marc,

The itemTemplate can handle string or Template as a passed value. The Template interface has a factory function which means that you can create your template as follows:

var list = new ListView(); // create or getViewById the list-view
list.items = [5, 4, 3]; // set some mock list items
 
list.itemTemplate = () => {
 
    // build the template layout
    var stack = new StackLayout();
    var lbl = new Label();
     
    // example for simple bind equal to XML <Label text="{{ $value }}"/>
    lbl.bind({ sourceProperty: "$value", targetProperty: "text" });
    stack.addChild(lbl);
 
    return stack;
}
 
page.content = list;


Regards,
Nikolay Iliev
Telerik by Progress
 

Visit the Telerik Verified Plugins Marketplace and get the custom Cordova plugin you need, already tweaked to work seamlessly with AppBuilder.

 
Tags
General Discussion
Asked by
Marc
Top achievements
Rank 1
Answers by
Nick Iliev
Telerik team
Share this question
or